Thursday, May 4, 2017

Android Interview questions and answers

1.    What is an ANR Exception in Android?
 ANR is short for Application Not Responding. Android systems show this dialog if the application is performing too much of task on the main thread or UI thread and been unresponsive for a long period of time. Create user thread or worker thread to avoid ANR exception.  By making use of AsynTask, one can avoid this exception.
2.     What is the difference between an implicit intent and explicit intent?
 There are two types of Intent implicit and explicit intent
1) Implicit Intent:-
Implicit intent when you call system default intent like send email, send SMS, dial number etc

Intent sendIntent = new Intent();
sendIntent.putExtra(Intent.EXTRA_TEXT, textMessage);

2) Explicit Intent:-
Explicit intent when you call you're on application activity from one activity to another
e.g. first activity to second activity

Intent intent = new Intent(MainActivity.this, SecondAct.class);

3.    What is Android?
It is an open-sourced operating system that is used primarily on mobile devices, such as cell phones and tablets. It is a Linux kernel-based system that’s been equipped with rich components that allows developers to create and run apps that can perform both basic and advanced functions.
4.    What is AAPT?
AAPT is short for Android Asset Packaging Tool. This tool provides developers with the ability to deal with zip-compatible archives, which includes creating, extracting as well as viewing its contents.
5.    Differentiate Activities from Services.
Activities can be closed, or terminated anytime the user wishes. On the other hand, services are designed to run behind the scenes, and can act independently. Most services run continuously, regardless of whether there are certain or no activities being executed.
6.    What are the core building blocks of android?
The core building blocks of android are:
Activity, View, Intent, Service, Content Provider, Fragment etc…
7.    Which language does Android support to develop an application?
Android applications are written by using the java (Android SDK) and C/C++ (Android NDK).
8.    What is Adapter in Android?
An adapter is used to create a child view to present the parent view items.
9.    What is adb?
Adb is short for Android Debug Bridge. It allows developers the power to execute remote shell commands. Its basic function is to allow and control communication towards and from the emulator port
10.  When is the onStop() method invoked?
A call to onStop method happens when an activity is no longer visible to the user, either because another activity has taken over or if in front of that activity
11.  How can the ANR be prevented?
One technique that prevents the Android system from concluding a code that has been responsive for a long period of time is to create a child thread. Within the child thread, most of the actual workings of the codes can be placed, so that the main thread runs with minimal periods of unresponsive times
12.  Why cannot you run standard Java bytecode on Android?
A. Android uses Dalvik Virtual Machine (DVM) which requires a special bytecode. We need to convert Java class files into Dalvik Executable files using an Android tool called "dx". In normal circumstances, developers will not be using this tool directly and build tools will care for the generation of DVM compatible files.
13.  How does an application run in isolation from other applications?
A. Each application gets its own Linux user ID and virtual machine which means that the application code runs in isolation from other applications.
14.   Which dialog boxes can you use in you Android application?
A. AlertDialog: an alert dialog box and supports 0 to 3 buttons and a list of selectable elements. ProgressDialog: an extension of AlertDialog and you may add buttons to it. It shows a progress wheel or a progress bar. DatePickerDialog: used for selecting a date by the user. TimePickerDialog: used for selecting time by the user.
15.  What is a ContentProvider and what is it typically used for?
A ContentProvider manages access to a structured set of data. It encapsulates the data and provide mechanisms for defining data security. ContentProvider is the standard interface that connects data in one process with code running in another process.
More information about content providers can be found here in the Android Developer’s Guide

16.  What is DDMS? Describe some of its capabilities.
DDMS is the Dalvik Debug Monitor Server that ships with Android. It provides a wide array of debugging features including:
·         port-forwarding services
·         screen capture
·         thread and heap information
·         network traffic tracking
·         incoming call and SMS spoofing
·         simulating network state, speed, and latency
·         location data spoofing

17.  What is the difference between a fragment and an activity? Explain the relationship between the two.

An activity is typically a single, focused operation that a user can perform (such as dial a number, take a picture, send an email, view a map, etc.). Yet at the same time, there is nothing that precludes a developer from creating an activity that is arbitrarily complex.
Activity implementations can optionally make use of the Fragment class for purposes such as producing more modular code, building more sophisticated user interfaces for larger screens, helping scale applications between small and large screens, and so on. Multiple fragments can be combined within a single activity and, conversely, the same fragment can often be reused across multiple activities. This structure is largely intended to foster code reuse and facilitate economies of scale.
A fragment is essentially a modular section of an activity, with its own lifecycle and input events, and which can be added or removed at will. It is important to remember, though, that a fragment’s lifecycle is directly affected by its host activity’s lifecycle; i.e., when the activity is paused, so are all fragments in it, and when the activity is destroyed, so are all of its fragments.
18.  What is the difference between Service and IntentService? How is each used?
Service is the base class for Android services that can be extended to create any service. A class that directly extends Service runs on the main thread so it will block the UI (if there is one) and should therefore either be used only for short tasks or should make use of other threads for longer tasks.
IntentService is a subclass of Service that handles asynchronous requests (expressed as “Intents”) on demand. Clients send requests through startService(Intent) calls. The service is started as needed, handles each Intent in turn using a worker thread, and stops itself when it runs out of work. Writing an IntentService can be quite simple; just extend the IntentService class and override the onHandleIntent(Intent intent) method where you can manage all incoming requests.
19.  What do ADT stands for?
ADT stands for Android development tool,This is useful to develop the applications and test the applications.

20.  What is a service in android?
The Service is like as an activity to do background functionalities without UI interaction.

21.  What is shared preferences in android?
Shared preferences are the simplest mechanism to store the data in XML documents.

22.  How is the use of web view in Android?
WebView is UI component that can display either remote web-pages or static HTML

23.  What are the different Storage Methods in android?

Android provides many options for storage of persistent data. It provides the solution according to your need. The storages which have been provided in Android are as follows:-

Shared Preferences: Store private primitive data in key-value pairs

Internal Storage: Store private data on the device memory.

External Storage: Store public data on the shared external storage.

SQLite Databases: Store structured data in a private database.

Network Connection: Store data on the web with your own network server

24.   How do you find any view element into your program?
Findviewbyid : Finds a view that was identified by the id attribute from the XML processed inActivity.OnCreate(Bundle).

25.  Singleton design pattern in java
Singleton patterns comes under creational design patterns. The Singleton's purpose is to control object creation, limiting the number of objects to one only.  Since there is only one Singleton instance, any instance fields of a Singleton will occur only once per class, just like static fields. Singletons often control access to resources such as database connections or sockets.
Singleton ensures that a class has only one instance, and provide a global point of access to it.

public class Singleton {
  // Private constructor prevents instantiation from other classes
  private Singleton() {}

   * SingletonHolder is loaded on the first execution of Singleton.getInstance()
   * or the first access to SingletonHolder.INSTANCE, not before.
  private static class SingletonHolder {
    private static final Singleton INSTANCE = new Singleton();

  public static Singleton getInstance() {
    return SingletonHolder.INSTANCE;

26.  How to check service is running in background or not?
Use below code to check whether service is running or not
private boolean isMyServiceRunning(Class serviceClass) {
  ActivityManager actManager = (ActivityManager)
  for (RunningServiceInfo service : actManager
    .getRunningServices(Integer.MAX_VALUE)) {
   if (serviceClass.getName().equals(service.service.getClassName())) {
    return true;
  return false;

Other Android Qns

  • How does the Android notification system work?
  • How can two distinct Android apps interact? (several answers)
  • Describe Activities. 
  • What are the four states of the Activity Lifecycle? 
  • What are the seven callback methods of an Activity used to perform operations when the Activity transitions between states? 
  • What is the difference between a fragment and an activity? Explain the relationship between the two.
  • What is the difference between Serializable and Parcelable? Which is the best approach in Android?
  • What are "launch modes"?
  • What are Intents? 
  • What is an Implicit Intent? 
  • What is an Explicit Intent? 
  • Describe three common use cases for using an Intent.
  • What is a Service? 
  • What is a ContentProvider and what is it typically used for? 
  • What is a Fragment?   
  • What is AndroidManifest.xml used for? Give examples of what kind of data you would add to it. 
  • Describe how broadcasts and intents work to be able to pass messages around your app.
  • What is the Dalvik Virtual Machine?
  • What are different ways to store data in your Android app? 
  • Android appplication components 
  • What is the relationship between the life cycle of an AsyncTask and an Activity? What problems can this result in? How can these problems be avoided?
  • What is the difference between Service and IntentService? How is each used?
  • What is a Sticky Intent?
  • What is AIDL? 
  • What is dependency injection?
  • What are the different protection levels in permission? 

Android Design and XML

  • Explain the differences and similarities of Relative Layout and Linear Layout.
  • Explain the differences and similarities of List Views and Grid Views.
  • Describe how to implement XML namespaces.
  • Explain how to present different styles/drawables for a button depending on the state of the button (pressed, selected, etc.) using XML (no Java) 
  • for layout_width and layout_height, what's the difference between match_parent and wrap_content?
  • How do you implement Google's new Material Design in an Android application? 
  • Difference between View.GONE and View.INVISIBLE?

Android Networking

  • Have you use an HTTP Library, which, why, did you like it?
  • Describe how REST APIs work.
  • What are some typical methods of HTTP request/responses? 


  • Why does Android use SQLite?
  • What libraries have you used for interacting with databases and why did you choose them?
  • What are contract classes? 
  • How do you use the BaseColumns interface to describe your data schema? 

Friday, February 12, 2016

Way to check Android Serivce is running or not

Use below code to check whether service is running or not
private boolean isMyServiceRunning(Class serviceClass) { 
  ActivityManager actManager = (ActivityManager) 
  for (RunningServiceInfo service : actManager
    .getRunningServices(Integer.MAX_VALUE)) {
   if (serviceClass.getName().equals(service.service.getClassName())) {
    return true;
  return false;

Tuesday, February 2, 2016

Android ART vs DalvikVM

ART was introduced in KitKat (4.4):
– Available only through developer options
– Declared to be a “preview” release, use-at-your-own-risk
– Very little documentation, if any

In Lollipop, ART becomes the RunTime of choice
– Supersedes (all but buries) Dalvik
– Breaks compatibility with older DEX, as well as itself (in preview version)
– And still – very little documentation, if any

Dalvik Disadvantages
Introducing: ART
• ART was designed to address the shortcomings of Dalvik:
– Virtual machine maintenance is expensive
• Interpreter/JIT simply aren’t efficient as native code
• Doing JIT all over again on every execution is wasteful
• Maintenance threads require significantly more CPU cycles
• CPU cycles translate to slower performance – and shorter battery life
– Dalvik garbage collection frequently causes hangs/pauses
– Virtual machine architecture is 32-bit only
• Android is following iOS into the 64-bit space

Monday, January 11, 2016

Interact Android device and take screen short using python script

Here a complete python script which will be used to interact with device and take screen short.
Functionality of this scripit
  1. Save screenshort
  2. Lock the screen
  3. Unlock the screen
  4. Send touches to screen
to run this program, you need install python and tkinter ui plugin.
Save following code in 
import tkinter as tk
import sys
import signal
import string
import os
import subprocess
import time
from tkinter import W
from adb import ADB
import threading
import time
class Application(tk.Frame):

    def __init__(self, master=None):
        tk.Frame.__init__(self, master)

    def createWidgets(self):
        self.moving = False
        self.close = tk.Button(self, text="Exit", fg="red",
                                            command=root.destroy) = tk.Button(self, text="Save Screen", fg="blue", bg="yellow",
        self.filelabel = tk.Label(self, text="File Name")
        self.lock = tk.Button(self, text="Lock", fg="blue",
         self.unlock = tk.Button(self, text="UnLock", fg="blue",

        self.result = tk.Label(self, textvariable=res)     
        self.enter = tk.Entry(self, textvariable=filename)
        self.frame = tk.Frame(self, width=280, height=500, background='white')
        self.img = tk.PhotoImage(file="dummy.png")
        self.img = self.img.subsample(4, 4)           
        self.r = tk.Label(self.frame, image=self.img) 
        self.r.bind("<1>", self.OnMouseDown)
        self.r.bind("<B1-Motion>", self.OnMotion)
        self.r.bind("<ButtonRelease-1>", self.OnMouseRelease)
        self.filelabel.grid(row=0, column=0)
        self.enter.grid(row=0, column=1), column=1)
        self.close.grid(row=1, column=1)
        self.lock.grid(row=1, column=2)
        self.unlock.grid(row=1, column=3)
        self.result.grid(row=2, column=1) 
         self.frame.grid(row=4, column=1); 
         self.thread = threading.Thread(, args=())
        self.thread.daemon = True                            # Daemonize thread

        self.thread1 = threading.Thread(target=self.run1, args=())
        self.thread1.daemon = True                            # Daemonize thread
     def OnMouseDown(self, event):
        #print("frame coordinates: %s/%s" % (event.x*4, event.y*4))
        #print("root coordinates: %s/%s" % (event.x_root, event.y_root))
        cm = "adb shell input tap "+str(event.x*4)+" "+str(event.y*4)   
        #print("Sending key events....");
        sm = subprocess.Popen(cm.split())

    def say_hi(self):
        print("hi there, everyone!")

    def OnMotion(self, event):
        deltax =  event.x_root - event.x
        deltay =  event.y_root- event.y
        #x = self.winfo_x() + deltax
        #y = self.winfo_y() + deltay
        #self.geometry("+%s+%s" % (x, y))
        self.moving = True
        print("move...%s %s delta %s %s" %(event.x*4, event.y*4, deltax*4, deltay*4));
        self.movecommand = "adb shell input swipe "+ str(event.x*4)+" "+str(event.y*4)+" "+str(deltax*4)+" "+str(deltay*4)

    def OnMouseRelease(self, event):
            s = subprocess.Popen(self.movecommand.split())
            self.moving = False  

    def run(self):   
        while True:
            # Do something
            #print('calling #print...')
     def run1(self):   
        while True:
            # Do something
                #print('setup image...')
                self.img1 = tk.PhotoImage(file="temp.png")
                self.img1 = self.img1.subsample(4, 4)
                self.r.configure(image = self.img1)
                self.r.image = self.img1
     def lock_screen(self):
        c = 'adb shell input keyevent 26'       
        s = subprocess.Popen(c.split())
    def unlock_screen(self):
        c1 = 'adb shell input keyevent 82'      
        s = subprocess.Popen(c1.split()) 
     def takeScreenShort(self):
        #res.set("Saved temp.png successfully");
        self.img1 = tk.PhotoImage(file="temp.png")
        self.img1 = self.img1.subsample(4, 4)
        self.r.configure(image = self.img1)
        self.r.image = self.img1 
 root = tk.Tk()
obj = ADB()
filename = tk.StringVar()
res = tk.StringVar()
app = Application(master=root)
app.master.title("Screen Capture")
app.master.minsize(450, 250)
class ADB(object):

    def call(self, command):
        command_result = ''
        command_text = 'adb %s' % command
        results = os.popen(command_text, "r")
        while 1:
            line = results.readline()
            if not line: break
            command_result += line
        return command_result

    def devices(self):
        result ="devices")
        devices = result.partition('\n')[2].replace('\n', '').split('\tdevice')
        return [device for device in devices if len(device) > 2]

    def upload(self, fr, to):
        result ="push " + fr + " " + to)
        return result
    def get(self, fr, to):
        result ="pull " + fr + " " + to)
        return result

    def install(self, param):
        data = param.split()
        if data.length == 1:
            result ="install " + param[0])
        elif data.length == 2:
            result ="install " + param[0] + " " + param[1])
        return result

    def uninstall(self, package):
        result ="shell pm uninstall " + package)
        return result

    def clearData(self, package):
        result ="shell pm clear " + package)
        return result

    def shell(self, command):
        result ="shell " + command)
        return result
    def kill(self, package):
        result ="kill " + package)
        return result

    def start(self, app):
        pack = app.split()
        result = "Nothing to run"
        if pack.length == 1:
            result ="shell am start " + pack[0])    
        elif pack.length == 2:
            result ="shell am start " + pack[0] + "/." + pack[1])
        elif pack.length == 3:
            result ="shell am start " + pack[0] + " " + pack[1] + "/." + pack[2])
        return result

    def screen(self, res):
        result ="am display-size " + res)
        return result

    def dpi(self, dpi):
        result ="am display-density " + dpi)
        return result

    def screenRecord(self, param):
        params = param.split()
        if params.length == 1:
            result ="shell screenrecord " + params[0])
        elif params.length == 2:
            result ="shell screenrecord --time-limit " + params[0] + " " + params[1])
        return result

    def screenShot(self, output):"shell screencap -p /sdcard/temp_screen.png")
        self.get("/sdcard/temp_screen.png", output)"shell rm /sdcard/temp_screen.png")

And now run your python script.. Happy coding...

Thursday, January 8, 2015

Find back stack activities in an android application

An application usually contains multiple activities. A task is a collection of activities that users interact with when performing a certain job. The activities are arranged in a stack (the back stack), in the order in which each activity is opened. The device Home screen (Launcher Application) is the starting place for most tasks.

Finding list of activities in back stack can be done two ways.
1. Using ADB command
2. Using ActivityManager.

1. Using ADB command:
 An ADB (Android Debug Bridge) is a very useful tool for debugging android application. List some useful commands as follows.

1. adb shell dumpsys activity activities  -> displays list of activities in back stack

2. adb shell dumpsys activity process  -> displays list process in back stack

3. adb shell dumpsys activity intents  -> displays list of pending intents in back stack

4. adb shell dumpsys activity broadcast  -> displays list of broadcast in back stack

5. adb shell dumpsys activity services  -> displays list of services running in back stack

Note: Use grep command for filtering.

2. Using ActivityManager
 Use following line of code to get list of activities in stack.

ActivityManager m = (ActivityManager) ctx .getSystemService(ctx.ACTIVITY_SERVICE); List<RunningTaskInfo> runningTaskInfoList = m.getRunningTasks(10); Iterator<RunningTaskInfo> itr = runningTaskInfoList.iterator(); while (itr.hasNext()) { RunningTaskInfo runningTaskInfo = (RunningTaskInfo); int id =; CharSequence desc = runningTaskInfo.description; int numOfActivities = runningTaskInfo.numActivities; String topActivity = runningTaskInfo.topActivity .getShortClassName(); }

Thursday, November 27, 2014

Dalvik VM Internals - Video Tutorials

Dalvik VM Internals

Dan Bornstein (Google)

Dalvik — the virtual machine with the unusual name — runs your code on Android. Join us to learn about the motivation for its design and get
some details about how it works. You'll also walk away with a few tips for how to write code that works well with the platform. Be prepared
for a deep dive into technical details. Questions encouraged!

Presentation Slides