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

Building an Android Application Video Tutorial

Jason Chen (Google) This session is a practical introduction to building Android applications using the SDK and developer tools. Will walk through building a non-trivial application and use it as the basis for discussing the various facets of the Android application framework.

Monday, November 3, 2014

Java Lambda Expression

Lambdas (also known as closures) are the biggest and most awaited language change in the whole Java 8 release. A lambda expression is an anonymous function. Simply put, it's a method without a declaration, i.e., access modifier, return value declaration, and name. 

To create a lambda expression, you specify input parameters (if any) on the left side of the lambda operator =>, and you put the expression or statement block on the other side. For example, the lambda expression x => x * x specifies a parameter that’s named x and returns the value of x squared. You can assign this expression to a delegate type

    1. Reduced typing. 
    2. No need to specify the name of the function,
    3. No need to specify return type, and its access modifier. 
    4. When reading the code you don't need to look elsewhere for the method's definition. 

Full Working Code:
    ArrayList<Student> list = new ArrayList<Student>();
    Student s = new Student("AAA");
    Student s1 = new Student("BBB");
    Student s2 = new Student("CCC");

   //Lambda expression   
    list.forEach( e -> {
      Student res= (Student)e;
      System.out.println( ) ;

class Student{
  public String name; 
  public Student(String name){ name;

Wednesday, October 29, 2014

Android makeIn/fadeIn and makeOut/fadeOut Animation

If you want to make swipe in/out animation, Android by default provides a utility class called AnimationUtils. The class AnimationUtils Defines common utilities for working with animations.

1. Swipe out/ Fade out Effect.
The AnimationUtils class have static method called makeOutAnimation , used to exhibit swipe out/fade out animations.

Animation anim = AnimationUtils.makeOutAnimation(context, fromLeft);

It creates an animation for objects becoming visible. Uses a slide and fade effect.

2. Swipe In/ Fade In Effect.
The AnimationUtils class have static method called makeInAnimation , used to exhibit swipe out/fade out animations.

Animation anim = AnimationUtils.makeInAnimation(context, fromLeft);

It creates an animation for objects becoming invisible. Uses a slide and fade effect.

Android Application Designing for Performance

An Android application should be fast. Well, it's probably more accurate to say that it should be efficient. That is, it should execute as efficiently as possible in the mobile device environment, with its limited computing power and data storage, smaller screen, and constrained battery life.
In this blog I am providing best practices to follow to design for performance.

1. Avoid Creating Objects
Object creating in android is more expensive than creating object in Java. Try to avoid creating objects as possible as you do. More objects mean more work to GC. More works to GC means little "hiccups" in the user experience.

Generally speaking, avoid creating short-term temporary objects if you can. Fewer objects created mean less-frequent garbage collection, which has a direct impact on user experience.  If possible pool the objects, so it can be reused.

2.  Keep Blocking Operations Off the Main UI Thread
Use AsyncTask, Thread, IntentService, or Custom background service to do the heavy work. Use Loaders to simplify state management of long loading data, such as cursors. You cannot afford for your application to lag or freeze while some processing is going on. If an operation takes time and resources, offload that processing and perform it asynchronously so that your application remains responsive and the user can go about their business

3. Use Native Methods
 C/C++ code that easily runs 10-100x faster than doing the same thing in a Java loop.

4. Prefer Virtual Over Interface
Suppose you have a HashMap object. You can declare it as a HashMap or as a generic Map:

Map myMap1 = new HashMap();

HashMap myMap2 = new HashMap();
Which is better?

Conventional wisdom says that you should prefer Map, because it allows you to change the underlying implementation to anything that implements the Map interface. Conventional wisdom is correct for conventional programming, but isn't so great for embedded systems. Calling through an interface reference can take 2x longer than a virtual method call through a concrete reference.

If you have chosen a HashMap because it fits what you're doing, there is little value in calling it a Map. Given the availability of IDEs that refractor your code for you, there's not much value in calling it a Map even if you're not sure where the code is headed. (Again, though, public APIs are an exception: a good API usually trumps small performance concerns.)

5. Prefer Static Over Virtual
If you don't need to access an object's fields, make your method static. It can be called faster, because it doesn't require a virtual method table indirection. It's also good practice, because you can tell from the method signature that calling the method can't alter the object's state.

6. Avoid Internal Getters/Setters
In native languages like C++ it's common practice to use getters (e.g. i = getCount()) instead of accessing the field directly (i = mCount). This is an excellent habit for C++, because the compiler can usually inline the access, and if you need to restrict or debug field access you can add the code at any time.

On Android, this is a bad idea. Virtual method calls are expensive, much more so than instance field lookups. It's reasonable to follow common object-oriented programming practices and have getters and setters in the public interface, but within a class you should always access fields directly.

7. Declare Constants Final
Consider the following declaration at the top of a class:

static int intVal = 42;
static String strVal = "Hello, world!";
The compiler generates a class initializer method, called <clinit>, that is executed when the class is first used. The method stores the value 42 into intVal, and extracts a reference from the classfile string constant table for strVal. When these values are referenced later on, they are accessed with field lookups.

We can improve matters with the "final" keyword:
static final int intVal = 42;
static final String strVal = "Hello, world!";
The class no longer requires a <clinit> method, because the constants go into classfile static field initializers, which are handled directly by the VM. Code accessing intVal will use the integer value 42 directly, and accesses to strVal will use a relatively inexpensive "string constant" instruction instead of a field lookup.

Declaring a method or class "final" does not confer any immediate performance benefits, but it does allow certain optimizations. For example, if the compiler knows that a "getter" method can't be overridden by a sub-class, it can inline the method call.

You can also declare local variables final. However, this has no definitive performance benefits. For local variables, only use "final" if it makes the code clearer (or you have to, e.g. for use in an anonymous inner class).

8. Use Enhanced For Loop Syntax with Caution
The enhanced for loop (also sometimes known as "for-each" loop) can be used for collections that implement the Iterable interface. With these objects, an iterator is allocated to make interface calls to hasNext() and next(). With an ArrayList, you're better off walking through it directly, but for other collections the enhanced for loop syntax will be equivalent to explicit iterator usage.

Nevertheless, the following code shows an acceptable use of the enhanced for loop:

public class Foo {
    int mSplat;
    static Foo mArray[] = new Foo[27];

    public static void zero() {
        int sum = 0;
        for (int i = 0; i < mArray.length; i++) {
            sum += mArray[i].mSplat;

    public static void one() {
        int sum = 0;
        Foo[] localArray = mArray;
        int len = localArray.length;

        for (int i = 0; i < len; i++) {
            sum += localArray[i].mSplat;

    public static void two() {
        int sum = 0;
        for (Foo a: mArray) {
            sum += a.mSplat;

zero() retrieves the static field twice and gets the array length once for every iteration through the loop.

one() pulls everything out into local variables, avoiding the lookups.

two() uses the enhanced for loop syntax introduced in version 1.5 of the Java programming language. The code generated by the compiler takes care of copying the array reference and the array length to local variables, making it a good choice for walking through all elements of an array. It does generate an extra local load/store in the main loop (apparently preserving "a"), making it a teensy bit slower and 4 bytes longer than one().

To summarize all that a bit more clearly: enhanced for loop syntax performs well with arrays, but be cautious when using it with Iterable objects since there is additional object creation.

9. Avoid Enums
Enums are very convenient, but unfortunately can be painful when size and speed matter. For example, this:

public class Foo {
   public enum Shrubbery { GROUND, CRAWLING, HANGING }
turns into a 900 byte .class file (Foo$Shrubbery.class). On first use, the class initializer invokes the <init> method on objects representing each of the enumerated values. Each object gets its own static field, and the full set is stored in an array (a static field called "$VALUES"). That's a lot of code and data, just for three integers.


Shrubbery shrub = Shrubbery.GROUND;
causes a static field lookup. If "GROUND" were a static final int, the compiler would treat it as a known constant and inline it.

The flip side, of course, is that with enums you get nicer APIs and some compile-time value checking. So, the usual trade-off applies: you should by all means use enums for public APIs, but try to avoid them when performance matters.

In some circumstances it can be helpful to get enum integer values through the ordinal() method. For example, replace:

for (int n = 0; n < list.size(); n++) {
    if (list.items[n].e == MyEnum.VAL_X)
       // do stuff 1
    else if (list.items[n].e == MyEnum.VAL_Y)
       // do stuff 2

   int valX = MyEnum.VAL_X.ordinal();
   int valY = MyEnum.VAL_Y.ordinal();
   int count = list.size();
   MyItem items = list.items();

   for (int  n = 0; n < count; n++)
        int  valItem = items[n].e.ordinal();

        if (valItem == valX)
          // do stuff 1
        else if (valItem == valY)
          // do stuff 2

In some cases, this will be faster, though this is not guaranteed.

10. Use Package Scope with Inner Classes
Consider the following class definition:

public class Foo {
    private int mValue;

    public void run() {
        Inner in = new Inner();
        mValue = 27;

    private void doStuff(int value) {
        System.out.println("Value is " + value);

    private class Inner {
        void stuff() {

The key things to note here are that we define an inner class (Foo$Inner) that directly accesses a private method and a private instance field in the outer class. This is legal, and the code prints "Value is 27" as expected.

The problem is that Foo$Inner is technically (behind the scenes) a totally separate class, which makes direct access to Foo's private members illegal. To bridge that gap, the compiler generates a couple of synthetic methods:

/*package*/ static int Foo.access$100(Foo foo) {
    return foo.mValue;
/*package*/ static void Foo.access$200(Foo foo, int value) {

The inner-class code calls these static methods whenever it needs to access the "mValue" field or invoke the "doStuff" method in the outer class. What this means is that the code above really boils down to a case where you're accessing member fields through accessor methods instead of directly. Earlier we talked about how accessors are slower than direct field accesses, so this is an example of a certain language idiom resulting in an "invisible" performance hit.

We can avoid this problem by declaring fields and methods accessed by inner classes to have package scope, rather than private scope. This runs faster and removes the overhead of the generated methods. (Unfortunately it also means the fields could be accessed directly by other classes in the same package, which runs counter to the standard OO practice of making all fields private. Once again, if you're designing a public API you might want to carefully consider using this optimization.)

11. Avoid Float
Before the release of the Pentium CPU, it was common for game authors to do as much as possible with integer math. With the Pentium, the floating point math co-processor became a built-in feature, and by interleaving integer and floating-point operations your game would actually go faster than it would with purely integer math. The common practice on desktop systems is to use floating point freely.

Unfortunately, embedded processors frequently do not have hardware floating point support, so all operations on "float" and "double" are performed in software. Some basic floating point operations can take on the order of a millisecond to complete.

Also, even for integers, some chips have hardware multiply but lack hardware divide. In such cases, integer division and modulus operations are performed in software — something to think about if you're designing a hash table or doing lots of math.

12. Some Sample Performance Numbers
To illustrate some of our ideas, here is a table listing the approximate run times for a few basic actions. Note that these values should NOT be taken as absolute numbers: they are a combination of CPU and wall clock time, and will change as improvements are made to the system. However, it is worth noting how these values apply relative to each other — for example, adding a member variable currently takes about four times as long as adding a local variable.

Add a local variable
Add a member variable
Call String.length()
Call empty static native method
Call empty static method
Call empty virtual method
Call empty interface method
Call Iterator:next() on a HashMap
Call put() on a HashMap
Inflate 1 View from XML
Inflate 1 LinearLayout containing 1 TextView
Inflate 1 LinearLayout containing 6 View objects
Inflate 1 LinearLayout containing 6 TextView objects
Launch an empty activity

13. Closing Notes
The best way to write good, efficient code for embedded systems is to understand what the code you write really does. If you really want to allocate an iterator, by all means use enhanced for loop syntax on a List; just make it a deliberate choice, not an inadvertent side effect.

Forewarned is forearmed! Know what you're getting into! Insert your favorite maxim here, but always think carefully about what your code is doing, and be on the lookout for ways to speed it up.

Tuesday, October 14, 2014

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.

Singleton applications

1.     Abstract Factory, Builder, and Prototype can use Singleton in their implementation.
2.     Facade objects are often Singletons because only one Facade object is required.
3.     State objects are often Singletons.
4.     The advantage of Singleton over global variables is that you are absolutely sure of the number of instances when you use Singleton, and, you can change your mind and manage any number of instances.
5.     The Singleton design pattern is one of the most inappropriately used patterns. Singletons are intended to be used when a class must have exactly one instance, no more, no less. Designers frequently use Singletons in a misguided attempt to replace global variables. A Singleton is, for intents and purposes, a global variable. The Singleton does not do away with the global; it merely renames it.
6.     When is Singleton unnecessary? Short answer: most of the time. Long answer: when it's simpler to pass an object resource as a reference to the objects that need it, rather than letting objects access the resource globally. The real problem with Singletons is that they give you such a good excuse not to think carefully about the appropriate visibility of an object. Finding the right balance of exposure and protection for an object is critical for maintaining flexibility.
7.     Our group had a bad habit of using global data, so I did a study group on Singleton. The next thing I know Singletons appeared everywhere and none of the problems related to global data went away. The answer to the global data question is not, "Make it a Singleton." The answer is, "Why in the hell are you using global data?" Changing the name doesn't change the problem. In fact, it may make it worse because it gives you the opportunity to say, "Well I'm not doing that, I'm doing this" – even though this and that are the same thing.

Check list

1.     Define a private static attribute in the "single instance" class.
2.     Define a public static accessor function in the class.
3.     Do "lazy initialization" (creation on first use) in the accessor function.
4.     Define all constructors to be protected or private.
5.     Clients may only use the accessor function to manipulate the Singleton.

Singleton Implementation

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;