SlideShare a Scribd company logo
1 of 95
Download to read offline
Introduction (part I):
Java and Android basics

   Alexey Golubev, Dmitry Lukashev
What is the plan?




         Java +Android            Android UI            Android in Action
               (basics)
                                 Layouts, ListView,        Screen rotation,
         JVM, GC, Threads,                                Memory analyze,
         SDK, NDK, Activity,   Menu, Dialog, Widgets,
                                 Tips & tricks, etc.      AIDL, SAX, Debug,
           Code style, etc.                                 Wakelock, etc.

             Part I                 Part II                  Part III
Part I: Introduction

What is this about?
• Introduction to Java world
  • JVM, Dalvik VM, JIT
  • GC, multithreading, collections, etc.
• Android Basics
  • Architecture
  • Building blocks, SDK, NDK, etc.
  • NDK demo
Java overview

•   Sun VM, Dalvik VM, JIT
•   Garbage collection
•   References
•   Exceptions
•   Threads
•   Synchronization
•   Collections
•   Wrapper classes
•   Java and Android code style
Where to start

•   http://developer.android.com/
•   http://source.android.com/
•   http://android.git.kernel.org/
•   http://android-developers.blogspot.com/
Java overview

•   Sun VM, Dalvik VM, JIT
•   Garbage collection
•   References
•   Exceptions
•   Threads
•   Synchronization
•   Collections
•   Wrapper classes
•   Java and Android code style
JVM

                                Class loader
      class files
                                 subsystem


                             The pc register (program counter)
                    Thread
                             JVM Stack
                             Native methods stacks
                             Heap
                     VM
                             Method Area
                    Сlass    Runtime Constant Pool


                                                                 native
                    Execution            Native method           method
                     engine                interface             libraries
Dalvik VM

• Was written by Dan Bornstein
• Transform class files into DEX
• It is VM…
   –   integrated with Linux
   –   uses shared memory, mmap
   –   for OS without swap space
   –   while powered by a battery
   –   zygote
• The Dalvik VM is register-based: fewer
  instructions, code units, instructions
• Verification & optimization at           Give me your huddled bytecodes
  installation time                          yearning to run free. And I lift
                                           the light beside the coder’s door
DEX file – shared constant pool
      .jar file
      .class file
     heterogeneous                .dex file
      constant pool
                                    string_ids    “Hello World”
                                  constant pool   “Lcom/data/Data”
       other data
                                    type_ids      int
                                  constant pool   String[ ]
      .class file
                                    proto_ids     String fn()
     heterogeneous                constant pool   void fn(int)
      constant pool
                                    field_ids     String.offset
                                  constant pool   Integer.MAX_VALUE
       other data
                                   method_ids     PrintStream.println(…)
                                  constant pool   Collection.size()
      .class file
     heterogeneous                 other data
      constant pool


       other data
DEX file – memory saving
•   minimal repetition
•   per-type pools (implicit typing)
•   implicit labeling

common system libraries
(U) 21445320 — 100% (uncompressed jar file)
(J) 10662048 — 50% (compressed jar file)
(D) 10311972 — 48% (uncompressed dex file)

web browser app
(U) 470312 — 100%
(J) 232065 — 49%
(D) 209248 — 44%

•   Google claims that Dalvik bytecode is more efficient than Sun’s stack
    bytecode
JIT (since Android 2.2)

•   Translates byte code to optimized native code at run time
•   Part of the open source
•   Trace JIT vs Method JIT
•   Trace JIT
    –   Minimizing memory usage critical for mobile devices (100K)
    –   Important to deliver performance boost quickly
    –   Trace request is built during interpretation
    –   Compiled traces chained together in translation cache
    –   Per process translation cache
• Leave open the possibility of supplementing with method-
  based JIT
Java overview

•   Sun VM, Dalvik VM, JIT
•   Garbage collection
•   References
•   Exceptions
•   Threads
•   Synchronization
•   Collections
•   Wrapper classes
•   Java and Android code style
Garbage collection

• GC is under control of the JVM
• An object is eligible for garbage                  i2
                                                                       The heap
  collection when no live thread can
  access it                                     i3                                 i2.n

• System.gc();                                 i4
  Runtime.getRuntime().gc()
• static – variables with the longest
  life time                                                                               i3.n
                                                                      i4.n

public class Island {
    Island i;
    public static void main(String[] args) {
        Island i2 = new Island();
        Island i3 = new Island();
        Island i4 = new Island();                         “Islands of Isolation”
        i2.n = i3; i3.n = i4; i4.n = i2;                                                         x
        i2 = null; i3 = null; i4 = null;
        Island x = new Island(); x = null;
    }
}
Mark and Sweep example

•   Obtain locks and suspend threads                                Parallel mark bits in
                                                                    Dalvik VM (separate from
•   Mark phase                                                      other heap memory)

     – Process of identifying all objects reachable from the root set.
     – All “live” objects are marked by setting a mark bit in the mark bit vector.
•   Sweep phase
     – Sweep phase identifies all the
        objects that have been allocated,
        but no longer referenced.
•   Compaction (optional)
     – Once garbage has been removed,
        we consider compacting the
        resulting set of objects to remove
        spaces between them.
•   Release locks and resume threads
Generational GC

• Most recently created objects – most likely to become
  unreachable quickly


                  Young Generation   Old Generation



• Minor Collection – takes place only in the young generation,
  normally done through direct copying – very efficient
• Major Collection – takes place in the new and old generation
  and uses the normal mark/sweep (+compact) algorithm
Strings

• Strings are immutable in Java                   String x = “Hi";

String s1 = "abc"; // 1 object, 1 reference
String s2 = "abc";                                               The heap
// s1 == s2
String s3 = new String("abc"); // 2                   “Hi”
objects, 1 reference                          x
String s4 = new String("abc");
// s3 != s4

// optimization by interning strings
                                                  x = x.concat(" GTUG!");
s3 = s3.intern();
s4 = s4.intern();
                                                                 The heap
• Use StringBuffer, StringBuilder
                                                      “Hi”
• Set initial capacity of StringBuilder       x

                                                             “Hi GTUG”
Quiz
class Foo {
    int[] mArray = {
              1, 2, 3, 4, 5
    };
}
                                                           [ ref0, ref1, ref2]

public class Test {
    public static void main(String[] args) {
         Foo[] fa = new Foo[3];                             Foo()       []
         fa[0] = new Foo();
         Foo f = new Foo();                                                      Foo()   []
         fa[1] = f;
         f = null;
         fa[1] = null;
         // how many objects were created at this point?
         // how many are eligible for gc()?
    }
}
Performance

• Do not allocate memory as much as you can
• GC is slow (~x00 ms on Android device)
• Decrease number of objects – GC will work faster (i.e.
  StringBuffer vs String)
• Use primitive types for arrays (int vs Integer)
• Use special methods: String.indexOf(), substring(), etc.
• Use exact class types instead of interfaces (i.e. HashMap
  instead of Map) on devices without JIT
• Use static where possible           ArrayList<MyClass> mList = new
• Avoid internal getters/setters      ArrayList<MyClass>();
                                      ...

• Use enhanced for-loop syntax        for (MyClass next : mList) {
                                          ...
                                          }
Java overview

•   Sun VM, Dalvik VM, JIT
•   Garbage collection
•   References
•   Exceptions
•   Threads
•   Synchronization
•   Collections
•   Wrapper classes
•   Java and Android code style
References

• Strong reference: Object obj = new Object();
• SoftReference – soft references will be cleared before the JVM
  reports an out-of-memory condition (memory-sensitive cache)
• WeakReference – gc frees weakly reachable object when it
  founds it, avoid memory leaks (e.g.
  http://en.wikipedia.org/wiki/Flyweight_pattern)
• PhantomReference – is useful only to track the impending
  collection of the referring object. Must be used only with the
  ReferenceQueue class. Most often used for scheduling pre-
  mortem cleanup actions in a more flexible way than is possible
  with the Java finalization mechanism
SoftReference: simple cache


  private final HashMap<String, SoftReference<T>> mCache;

  public put(String key, T value) {
      mCache.put(key, new SoftReference<T>(value));
  }

  public T get(String key, ValueBuilder builder) {
      T value = null;
      SoftReference<T> reference = mCache.get(key);
      if (reference != null) {
          value = reference.get();
      }
      // Not in cache or gc'd
      if (value == null) {
          value = builder.build(key);
          mCache.put(key, new SoftReference<T>(value));
      }
      return value;
  }
git://android.git.kernel.org/platform/packages/apps/Mms.git/src/com/android/mms/model/ImageModel.java


package com.android.mms.model;
 public class ImageModel extends RegionMediaModel {
    private static final String TAG = "Mms/image";
    private static final int THUMBNAIL_BOUNDS_LIMIT = 480;
    private SoftReference<Bitmap> mBitmapCache = new SoftReference<Bitmap>(null);
  ...
    private Bitmap internalGetBitmap(Uri uri) {
        Bitmap bm = mBitmapCache.get();
        if (bm == null) {
            try {
                bm = createThumbnailBitmap(THUMBNAIL_BOUNDS_LIMIT, uri);
                if (bm != null) {
                    mBitmapCache = new SoftReference<Bitmap>(bm);
                }
            } catch (OutOfMemoryError ex) {
                // fall through and return a null bitmap.
                 // The callers can handle a null
                // result and show R.drawable.ic_missing_thumbnail_picture
            }
        }
        return bm;
    }
                                                                                     SoftReference
}
git://android.git.kernel.org/platform/frameworks/base.git/core/java/android/app/Dialog.java


package android.app;

public class Dialog implements DialogInterface, Window.Callback,
                        KeyEvent.Callback, OnCreateContextMenuListener {
    ...
    private static final class ListenersHandler extends Handler {
        private WeakReference<DialogInterface> mDialog;

        public ListenersHandler(Dialog dialog) {
            mDialog = new WeakReference<DialogInterface>(dialog);
        }

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case DISMISS:
                    ((OnDismissListener) msg.obj).onDismiss(mDialog.get());
                    break;
                case CANCEL:
                    ((OnCancelListener) msg.obj).onCancel(mDialog.get());
                    break;
                case SHOW:
                    ((OnShowListener) msg.obj).onShow(mDialog.get());
                    break;
            }
        }
    }                                                                                 WeakReference
}
finalize()

• The finalize() method is guaranteed to run once and only once
  before GC deletes an object
• GC makes no guarantees, finalize() may never run
• You can uneligibilize an object for GC within finalize()
• Do not use it for resource closing
Java overview

•   Sun VM, Dalvik VM, JIT
•   Garbage collection
•   References
•   Exceptions
•   Threads
•   Synchronization
•   Collections
•   Wrapper classes
•   Java and Android code style
Exceptions

try {
    // do stuff                         Object
} catch (SomeException e) {
    // do exception handling
} finally {
    // clean up                        Throwable
}

try {
    // do stuff
} finally {
                               Error                     Exception
    // clean up
}



  AssertionError                           RuntimeException
  StackOverflowError
  OutOfMemoryError
  NullPointerException
  IndexOfBoundException
  IOException
  SQLiteException
try/catch/finally (1)

class Test {


    private String data = "test";


    private int test() {
        try {
            System.out.println(data.length());
            return 0;
        } catch (NullPointerException e) {
                                                      4
            System.out.println("exception");
            return 1;                                 finally
        } finally {
                                                      result = 2
            System.out.println("finally");
            return 2;
        }
    }


    public static void main(String[] args) {
        Test t = new Test();
        System.out.println("result = " + t.test());
    }


}
try/catch/finally (2)

class Test {


    private String data;


    private int test() {
        try {
            System.out.println(data.length());
            return 0;
        } catch (NullPointerException e) {
                                                      exception
            System.out.println("exception");
            return 1;                                 finally
        } finally {
                                                      result = 2
            System.out.println("finally");
            return 2;
        }
    }


    public static void main(String[] args) {
        Test t = new Test();
        System.out.println("result = " + t.test());
    }


}
DefaultExceptionHandler

public class DefaultExceptionHandler implements UncaughtExceptionHandler {
        private UncaughtExceptionHandler mDefaultExceptionHandler;


        public DefaultExceptionHandler(UncaughtExceptionHandler pDefaultExceptionHandler)
        {
            mDefaultExceptionHandler = pDefaultExceptionHandler;
        }


        public void uncaughtException(Thread t, Throwable e) {
            mDefaultExceptionHandler.uncaughtException(t, e);
            t.getThreadGroup().destroy();
        }
    }



Thread.setDefaultUncaughtExceptionHandler(new
    DefaultExceptionHandler(Thread.getDefaultUncaughtExceptionHandler()));
Java overview

•   Sun VM, Dalvik VM, JIT
•   Garbage collection
•   References
•   Exceptions
•   Threads
•   Synchronization
•   Collections
•   Wrapper classes
•   Java and Android code style
Threads

• When it comes to threads, very little is guaranteed
• Create thread: extend java.lang.Thread or implement Runnable
  interface
• A thread is done being a thread when its target run() method
  completes
• Once a thread has been started, it can never be started again
• The order in which runnable threads are chosen is not
  guaranteed
• sleep(long ms), yield(), join(), setPriority(int priority), wait(),
  notify(), notifyAll()
Thread states




                                          Waiting/
                                          blocking

                                                       wait, sleep, join, lock



                                           yield
           New                 Runnable              Running                       Dead

                     start()                                   run() completes
         not alive                         alive                                 not alive
Java overview

•   Sun VM, Dalvik VM, JIT
•   Garbage collection
•   References
•   Exceptions
•   Threads
•   Synchronization
•   Collections
•   Wrapper classes
•   Java and Android code style
Synchronization

• Every Object in java has build-in lock
• Only methods or blocks can be synchronized
public static synchronized int getCount() {
    return count;
}

public static int getCount() {
    synchronized(MyClass.class) { // Class c = Class.forName(“MyClass”);
        return count;
    }
}


• notify(), join(), sleep(), yield() keep locks, wait() gives up lock
• synchronized keyword is not automatically inherited when
  subclasses override superclass method
Volatile

public class Task extends Thread {          class VolatileExample {
    private volatile boolean mIsStop;           int x = 0;
                                                volatile boolean v = false;
     public void run() {
                                                 public void writer() {
         while (!mIsStop) {                          x = 42;
             // do some stuff...                     v = true;
         }                                       }
     }
                                                 public void reader() {
                                                     if (v == true) {
     public void stopMe() {
                                                         // uses x - guaranteed to see 42.
         mIsStop = true;                             }
     }                                           }
}                                           }



volatile:
• Every thread accessing the field will read its current value before continuing, instead of
    (potentially) using a cached value
• Statements accessing the variable will be executed in the order they are written (Java 5 or
    later)
Singleton pattern example (1)
public class Singleton {
    private static final Singleton INSTANCE = new Singleton();


    private Singleton() {}


    public static Singleton getInstance() {
        return INSTANCE;
    }
                                                                     thread-safe
}

public class Singleton {
    private static Singleton sInstance;

    private Singleton() {}

    public static Singleton getInstance() {
        if (sInstance == null) {
            sInstance = new Singleton();
        }
        return sInstance;
                                                                         lazy init
    }
}                                                                non-thread-safe
Singleton pattern example (2)

public class Singleton {
    private static Singleton sInstance;

    private Singleton() {}

    public synchronized static Singleton getInstance() {
        if (sInstance == null) {
            sInstance = new Singleton();
        }                                                           lazy init
        return sInstance;
                                                                thread-safe
    }
}                                                          low performance
Singleton pattern example (3)
public class Singleton {
    private static Singleton sInstance;

    private Singleton() {}

    public static Singleton getInstance() {
        if (sInstance == null) {
            synchronized (Singleton.class) {
                if (sInstance == null) { // “Double-Checked Locking” idiom
                    sInstance = new Singleton();
                }
            }
        }
        return sInstance;
    }
}
Singleton pattern example (4)
public class Singleton {
    private volatile static Singleton sInstance;

    private Singleton() {}

    public static Singleton getInstance() {
        if (sInstance == null) {
            synchronized (Singleton.class) {
                if (sInstance == null) {
                    sInstance = new Singleton();
                }
            }
        }
        return sInstance;
    }
}                                                  lazy init & thread-safe (Java 5 or later)
Singleton pattern example (5)
public class Singleton {
    private Singleton() {}

    private static class SingletonHolder {
        private static final Singleton INSTANCE = new Singleton();
    }

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




                                              lazy init & thread-safe (for all Java version)
Quiz

public class Foo {

       private   static final int DELTA = 6;
       private   static Foo sInstance = new Foo();
       private   static int sBase = 7;
       private   int mX;

       private Foo() {
           mX = sBase + DELTA;
       }

       public static void main(String[] args) {
           System.out.println(Foo.sInstance.mX);
       }
}



What is the print?      6
Java overview

•   Sun VM, Dalvik VM, JIT
•   Garbage collection
•   References
•   Exceptions
•   Threads
•   Synchronization
•   Collections
•   Wrapper classes
•   Java and Android code style
Collection                         Collections

                Set                           List                  Queue




  HashSet              SortedSet



LinkedHashSet         NavigableSet         ArrayList     Vector       LinkedList    PriorityQueue
                                     1.6



                        TreeSet
                                                                        Map




                                                                                     SortedMap
  WeakHashMap
  ConcurrentHashMap
  CopyOnWriteArraySet                                   HashTable     HashMap       NavigableMap
                                                                                                    1.6
  etc…
                                                                    LinkedHashMap     TreeMap
Hash table

• Choosing a good hash function
• Collision resolution: separate chaining, open addressing
• Load factor

 Key    Hashcode Algorithm      Hashcode   19   Bob           19   Bob

 Alex   A(1)+L(12)+E(5)+X(24)   42
                                           33   Fred          33   Fred
 Bob    B(2)+O(15)+B(2)         19
                                           42   Alex   Dirk   42   Alex
 Dirk   D(4)+I(9)+R(18)+K(11)   42
                                                              43   Dirk
 Fred   F(6)+R(18)+E(5)+D(4)    33



• Find the right bucket (using hashCode())
• Search the bucket for the right element (using equals())
Contracts

The equals() contract
• Reflexive – x.equals(x)=true
• Symmetric – x.equals(y)=true -> y.equals(x)=true
• Transitive – x.equals(y)=true, y.equals(z)=true ->
  x.equals(z)=true
• Consistent – multiple invocations
• x.equals(null)=false

The hashCode() contract
                                                @Override
• Consistent during the app execution           public int hashCode() {
                                                    return 1;
• If x.equals(y) -> hash must be the same       }
Java overview

•   Sun VM, Dalvik VM, JIT
•   Garbage collection
•   References
•   Exceptions
•   Threads                       int

•   Synchronization
•   Collections
•   Wrapper classes
•   Java and Android code style
Wrapper Classes and Boxing (1)

• The wrapper classes correlate to primitive types
• Wrappers have two main functions:
       – To wrap primitives so that they can be handled like objects
       – To provide utility methods for primitives (conversions)
• Wrapper constructors can take String (except Character)
• As of Java 5, boxing allows to convert primitives to wrappers or
  vice versa automatically.
Integer x = 100;
x++;

int x2 = x.intValue();
x2++;
x = new Integer(x2);
Wrapper Classes and Boxing (2)

Integer i1 = 1000;
Integer i2 = 1000;
if (i1 != i2) System.out.println("i1!=i2");   i1!=i2
if (i1 == i2) System.out.println("i1==i2");


Integer i1 = 100;
Integer i2 = 100;
if (i1 != i2) System.out.println("i1!=i2");   I1==i2
if (i1 == i2) System.out.println("i1==i2");




JVM saves memory for:
• Boolean
• Byte
• Character from u0000 to u007f
• Short and Integer from -128 to 127
Java overview

•   Sun VM, Dalvik VM, JIT
•   Garbage collection
•   References
•   Exceptions
•   Threads
•   Synchronization
•   Collections
•   Wrapper classes
•   Java and Android code style
Java Code Style: why?

• 80% of the lifetime cost of a piece of software goes to maintenance
• Hardly any software is maintained for its whole life by the original
  author
• Code conventions improve the readability of the software, allowing
  engineers to understand new code more quickly and thoroughly
• Makes it easier to conduct code reviews

  http://developers.sun.com/sunstudio/products/archive/whitepapers/java-style.pdf
Comments, TODOs, etc.

• Comments
• TODO, FIXME, XXX
   – Use TODO comments for code that is temporary, a short-
     term solution, or good-enough but not perfect.
• Copyrights
Android Code Style (1)

• Import ordering
   – Android imports
   – Imports from third parties (com, junit, net, org)
   – java and javax
• Indentation
   – We use 4 space indents for blocks. We never use tabs. When in doubt,
     be consistent with code around you
   – We use 8 space indents for line wraps, including function calls and
     assignments
• Field Names
   –   Non-public, non-static field names start with m.
   –   Static field names start with s.
   –   Other fields start with a lower case letter.
   –   Public static final fields (constants) are ALL_CAPS_WITH_UNDERSCORES.
Android Code Style (2)

• Braces
   – Braces do not go on their own line; they go on the same line as the code
      before them
       if (condition) {
           body; // ok
       }

       if (condition) body; // ok - 1 line

       if (condition)
           body; // bad

• Line length
   – Each line of text in your code should be at most 100 characters long.
• Annotations, Logging
           http://source.android.com/submit-patches/code-style-guide
BAD Code Style sample (1)

for(int i=0;i<amount;++i)
    db.execSQL(sqls[i]);


public static final int sMaxSQLsInTransaction= 1000;

if (delayed == true) {
    ...
} else {
    ...
}




Good:
XmlHttpRequest getCustomerId
class Html
long id

Bad:
XMLHTTPRequest getCustomerID
class HTML
long ID
BAD Code Style sample (2)

  public static final boolean PushValues(String pattern,
          ArrayList<Integer> patternIds,/*OUT */ArrayList<String> values)
  {
      int idsAmount= (null != patternIds ? patternIds.size() : 0);
      if(0<idsAmount){
          final int patternLen=(null!=pattern ? pattern.length():0);
          if(0<patternLen){
              for(int i=0; i<idsAmount; ++i){
                  if(!pushValues(pattern,patternLen,patternIds.get(i),values)){
                       return (false);
                  }
              }
            return (true);
          }
      }
      return (false);
  }
BAD Code Style sample (2)

  public static final ArrayList<String> getValues(final String pattern,
          final ArrayList<Integer> patternIds) {
      ArrayList<Integer> result = new ArrayList<Integer>();
      if (pattern != null && pattern.length() > 0 && patternIds != null) {
          for (int patternId : patternIds) {
              ArrayList<Integer> values = getValuesForPatternId(pattern, patternId);
              if (values == null) {
                  return null;
              }
              result.addAll(values);
          }
      }
      return result;
  }
Let’s Have a Break!
       10 min
Android basics

•   Architecture Overview
•   Building Blocks
•   Manifest
•   System Services
•   Platform versions
•   Saving Application State
•   NDK
•   Make your code better
Android

•   Architecture Overview
•   Building Blocks
•   Manifest
•   System Services
•   Platform versions
•   Saving Application State
•   NDK
•   Make your code better
Android History

 • Jul 2005 – Google acquired Android Inc. (co-founded by Andy
   Rubin)
 • Nov 2007 – Google Android presentation and “early look”
   release

 Sep
2008                                    Éclair
           Mar    May     Sep     Oct            Dec
1.0        2009   2009   2009    2009            2009           Froyo

                                                          Jan       May
           1.1    1.5     1.6    2.0             2.0.1   2010       2010


                                                         2.1       2.2

              Cupcake
                         Donut                                             Gingerbread
Android Architecture Overview

                                                            Applications
                Home                 Contacts                  Phone                 Browser                  …
                                                  Application Framework
NDK / JNI




            Activity Manager     Window Manager         Content Providers          View System        Resource Manager

             Package Manager            Telephony Manager              Notification Manager          Location Manager

                                   Libraries                                                  Android Runtime
        Surface Manager          Media Framework              SQLite                             Core Libraries

             OpenGL | ES            FreeType                  WebKit                              Dalvik VM

                 SGL                   SSL                     libc

                                                            Linux Kernel
                Display Driver               Camera Driver             Flash Memory Driver          Binder (IPC) Driver

                Keypad Driver                 WiFi Driver                  Audio Drivers           Power Management
Android

•   Architecture Overview
•   Building Blocks
•   Manifest
•   System Services
•   Platform versions
•   Saving Application State
•   NDK
•   Make your code better
Android Application Building Blocks

• Activity
   – Presents UI
   – Each Activity is independent screen
   – Activity: setContentView(View)
• Service
   – Used for background operations
• BroadcastReceiver
   – Receive and process broadcast system or user events
• ContentProvider
   – Share application data with others
   – Data can be stored in FS, DB or even in memory
   – Communicate via ContentResolver
• Intent
   – Used to activate Activities, Services & BroadcastReceivers

                http://developer.android.com/guide/topics/fundamentals.html
Android Application

• Controls global Application state
• Extend Application class (android.app.Application)
   –   onCreate()
   –   onLowMemory()
   –   onTerminate()
   –   getApplicationContext() – to use it in classes, where is no
       Context
• Point custom Application class in AndroidManifest.xml
Android Context

Application Context                 Activity Context
• Non UI Context                    • Same as for Application, but specific
• startActivity(Intent)               to current Activity
• start /stopService(Intent)        • startActivityForResult(Intent) /
• sendBroadcast(Intent)               finish()
• register / unregisterReciever()   • bindService(Intent)
• Application FS, Preferences,      • UI: setContentView(View),
  Resources                           findViewById()
• getSystemService                  • User events handling (Keys,
                                      Touches, Trackball)
Android

•   Architecture Overview
•   Building Blocks
•   Manifest
•   System Services
•   Platform versions
•   Saving Application State
•   NDK
•   Make your code better
AndroidManifest.xml (1)
<?xml version="1.0" encoding="utf-8"?>
<manifest
     xmlns:android="http://schemas.android.com/apk/res/android"
     package="com.my.example"
     android:versionName="1.0 beta" android:versionCode="2">
     <application android:name=".MyApplication"
                    android:label="..." android:icon="...">
        <activity android:name=".MyActivity">
              <intent-filter>
                 <action android:name="android.intent.action.MAIN" />
                 <category android:name="android.intent.category.DEFAULT" />
                 <category android:name="android.intent.category.LAUNCHER" />
              </intent-filter>
        </activity>
        <service ... />
        <receiver ... />
        <provider ... />
     </application>
</manifest>
AndroidManifest.xml (2)

<activity android:name=".MyActivity"
          android:launchMode="singleTask"
          android:theme="@style/Theme.MyDialog" />
<service android:name=".MyService" android:process="new"/>
<receiver android:name=".MyReceiver" >
 <intent-filter>
   <action android:name= "android.intent.action.PACKAGE_REMOVED" />
   <category android:name= "android.intent.category.DEFAULT" />
   <data android:scheme= "package" />
 </intent-filter>
</receiver>
<provider android:name=".MyProvider"
          android:authorities="com.my.provider" />
AndroidManifest.xml (3)
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="..." package="com.my.example"
  android:versionName="1.0 beta" android:versionCode="2">
  <uses-permission android:name="android.permission.INTERNET" />
  <uses-permission android:name="android.permission.BLUETOOTH" />
  <uses-sdk
       android:minSdkVersion="3"
       android:targetSdkVersion="4"/>
  <supports-screens
       android:largeScreens="true"
       android:normalScreens="true"
       android:smallScreens="true"
       android:resizeable="true"
       android:anyDensity="true" />
   <application ...> ... </application>
</manifest>
AndroidManifest.xml (4)


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="..." package="com.my.example"
  android:versionName="1.0 beta" android:versionCode="2">
  <uses-configuration android:reqHardKeyboard="true"
                      android:reqTouchScreen="true" />
  <uses-feature android:name="android.software.live_wallpaper" />
  <uses-feature android:name="android.hardware.telephony" />
  <uses-feature android:name="android.hardware.telephony.cdma" />
  ...
</manifest>
Android

•   Architecture Overview
•   Building Blocks
•   Manifest
•   System Services
•   Platform versions
•   Saving Application State
•   NDK
•   Make your code better
Android System Services
Object getApplicationContext().getSystemService(String serviceName)

serviceName value         Service Class name    Description
(contsants in Context)
WINDOW_SERVICE            WindowManager         Controls on-screen windows
                                                and their parameters
LAYOUT_INFLATER_SERVICE   LayoutInflater        Inflates layout resources

POWER_SERVICE             PowerManager          Controls power management
NOTIFICATION_SERVICE      NotificationManager   Status bar notifications
CONNECTIVITY_SERVICE      ConnectivityManager   Handling network connections
WIFI_SERVICE              WifiManager           Handling Wi-Fi network status
TELEPHONY_SERVICE         TelephonyManager      Handling phone calls states
LOCATION_SERVICE          LocationManager       Controls location (GPS) updates
SENSOR_SERVICE            SensorManager         Controls sensor
…                         …                     …
Android

•   Architecture Overview
•   Building Blocks
•   Manifest
•   System Services
•   Platform versions
•   Saving Application State
•   NDK
•   Make your code better
Android Platform Versions

• May 2009 – platform ver. 1.5
• May 2010 – platform ver. 2.2
• Six platform releases in a year (platform ver.1.1 is
  hard to find on real phones)
• Platforms are back-compatible
• It is good point to be compatible with dominated
  platforms (1.5, 1.6, 2.0.1 and 2.1)
• To use advantages of the latest platform versions,
  Java Reflection mechanism should be used
Android Platform Fragmentation in the World




                                       December 2009




                                              June 2010
Android Platform Fragmentation in Russia

                                          Android 2.2 ; 0,5%    Android 2.0 ; 0,1%
                  Android 2.0.1 ; 0,6%




                         Android 1.6 ; 21,7%


                                                               Android 1.5 ; 43,6%




                          Android 2.1; 33,6%




• Data gathered by Flurry service in real application
• About 0.5% of 2.1 in Russia are custom ROMs
Java Reflection

• Originally used to inspect classes, interfaces, fields and
  methods at runtime, without knowing the names of them at
  compile time. It can be used for observing and/or modifying
  program execution at runtime
• Classes: Class, Method, Field, Constructor, etc.
// Without reflection
Foo foo = new Foo();
foo.hello();

// With reflection
Class cls = Class.forName("Foo");
Object foo = cls.newInstance();

Method method = cls.getMethod("hello", null);

method.invoke(foo, null);
Java Reflection and Android
public class ClassHolder {
    private static NewClass foo;
    public static void tryNewClass() {
        foo = new NewClass();
    }
}

try {
    ClassHolder.tryNewClass();
    // NewClass available
} catch (VerifyError e) {}

try {
    Method methodName = ClassName.class.getMethod(...);
    methodName.invoke(Object obj, Object... args);
} catch (NoSuchMethodException e) {}

try {
    Field fieldName = ClassName.class.getField(...);
    fieldName.getType(Object obj);
} catch (NoSuchFieldException e) {}
Java Reflection and Android (Example)
private static Field densityDpiField;
private static Field densityDpiLowResValue;
private static boolean sIsLowRes = false;
private static boolean sIsNormalRes = true;


static {
    try {
        densityDpiField = DisplayMetrics.class.getField("densityDpi");
        densityDpiLowResValue = DisplayMetrics.class.getField("DENSITY_LOW");
    } catch (NoSuchFieldException nfe) {
        // Old device - no density Field
    }
}
Java Reflection and Android (Example) (Cont.)
static {
    if (densityDpiField != null) {
        DisplayMetrics dMetrics = sContext.getResources().getDisplayMetrics();
        int densityDpi = 0;
        try {
            densityDpi = densityDpiField.getInt(dMetrics);
            sIsLowRes = (densityDpi == densityDpiLowResValue.getInt(dMetrics));
            sIsNormalRes =(densityDpi==densityDpiMediumResValue.getInt(dMetrics));
        } catch (Exception e) {
             sIsLowRes = false;
             sIsNormalRes = true;
        }
    }
}
Java Reflection and Android (Example) (Cont.)




public static int scaleToDensity(int dp_size) {
    if (dp_size == 0 || sIsNormalRes) {
          return dp_size;
    }
    return (int)(dp_size *
        sContext.getResources().getDisplayMetrics().density + 0.5f);
}
Android

•   Architecture Overview
•   Building Blocks
•   Manifest
•   System Services
•   Platform versions
•   Saving Application State
•   NDK
•   Make your code better
Saving State of Android Application
• Shared Preferences are stored in the application private data space
  and can be shared only inside this Application, but between launches
  and versions
• Instance of SharedPreferences class should be obtained:
Activity.getPreferences()
PreferenceManager.getDefaultSharedPreferences(Context ctx)
Context.getSharedPreferences(String name, int mode)

• To read:
mPreferences.getType(String key, T defValue);


• To write:
SharedPreferences.Editor editor = mPreferences.edit();
editor.putType(String key, T value);
editor.commit();

• SharedPreferences.OnSharedPreferenceChangeListener
Backup Application Data (android.app.backup – 2.2)
•   Perform backup arbitrary data to remote “cloud” storage
•   Easily perform backup of SharedPreferences and files
•   Restore the data saved to remote storage
•   Controlled by Android Backup Manager
    – Extend class BackupAgent and override onBackup() & onRestore()
    OR
    – Extend BackupAgentHelper to backup/restore SharedPreferences and
      files from internal storage
    – Add your agent to AndroidManifest.xml
        <application android:backupAgent=".MyBackupAgent" >

• BackupManager.dataChanged()/requestRestore()
• New bmgr tool for testing
  http://developer.android.com/guide/developing/tools/bmgr.html
• Full guide with examples:
  http://developer.android.com/guide/topics/data/backup.html
Android

•   Architecture Overview
•   Building Blocks
•   Manifest
•   System Services
•   Platform versions
•   Saving Application State
•   NDK
•   Make your code better
Android NDK (Native Development Kit)

• Provides ability and tools to embed components that make use
  of native code in Android applications
• Supports only restricted set of native libraries:
   – libc (C library) headers
   – libm (math library) headers
   – JNI interface headers
   – libz (Zlib compression) headers
   – liblog (Android logging) header
   – OpenGL ES 1.1 (since 1.6) and OpenGL ES 2.0 (3D graphics
     libraries, since 2.0) headers
   – libjnigraphics (Pixel buffer access) header (since 2.2)
   – A Minimal set of headers for C++ support
• For Windows Cygwin 1.7 (or higher) is needed
Android NDK Demo
Android

•   Architecture Overview
•   Building Blocks
•   Manifest
•   System Services
•   Platform versions
•   Saving Application State
•   NDK
•   Make your code better
Designing for Performance
                                        Action                              Time
• Use final for constants               Add a local variable                1

• Avoid enums                           Add a member variable               4
                                        Call String.length()                5
• Avoid float                           Call empty static native method     5

• Use local variables for access to     Call empty static method            12
                                        Call empty virtual method           12.5
  object fields inside loops (or more
                                        Call empty interface method         15
  than once)                            Call Iterator:next() on a HashMap   165
• Don’t use private scope with Inner    Call put() on a HashMap             600

  Classes                               Inflate 1 View from XML             22,000
                                        Inflate 1 LinearLayout containing   25,000
                                        1 TextView
                                        Inflate 1 LinearLayout containing   135,000
                                        6 TextView objects
                                        Launch an empty activity            3000,000
Designing for Responsiveness

• Application Not Responding (ANR) dialog:
   – No response to an input event (e.g. key press, screen
     touch) within 5 seconds
   – A BroadcastReceiver hasn't finished executing within 10
     seconds
• Quick Activity life-cycle methods (onCreate,
  onResume) and all other methods working on UI
  thread
• Use new Thread for long-time operations (i.e.
  network/database operations, expensive
  computations, bitmap resizing, etc.)
• Use ProgressBar or ProgressDialog to show
  “Loading…” or use splash screen when starting
  application
• To avoid long-time operations in BroadcastReceiver
  – start Service (not Activity!)
Designing for Seamlessness

• React correctly on system events (i.e. phone call)
        • onSaveInstanceState/onResumeInstanceState
        • onPause/onResume
        • TelephonyManager, etc.
• Share data using ContentProvider
• Use NotificationManager and Notifications from background
  processes (Service, BroadcastReceiver)
• Don’t overload a single Activity screen – use several Activities for
  correct dealing with history and Android “backstack” model
• Use Threads for long-time operations to avoid ANR
• Remember about multiple screen resolutions and multiple Android
  platform versions
• Assume the Network is slow (change speed in Eclipse DDMS for
  Emulator)
• Don’t assume Touchscreen or Keyboard
• Remember about battery life
Partners
Contacts

           Dmitry Lukashev
             http://ru.linkedin.com/in/dmitrylukashev
             dmitry.lukashev@gmail.com

           Alexey Golubev
             http://ru.linkedin.com/in/golubevalexey
             goalstudio@gmail.com



             Blog - http://android.amberfog.com/
Future reading

•   http://developer.android.com/guide/index.html
•   http://developer.android.com/resources/index.html
•   Soft, weak, phantom references: http://www.ibm.com/developerworks/library/j-
    refs/
    http://www.ibm.com/developerworks/java/library/j-jtp11225/index.html
    http://www.ibm.com/developerworks/java/library/j-jtp01246.html
•   JVM specification:
    http://java.sun.com/docs/books/jvms/second_edition/html/VMSpecTOC.doc.html
•   The Java Memory Model: http://www.cs.umd.edu/~pugh/java/memoryModel/
•   Dalvik VM: http://sites.google.com/site/io/dalvik-vm-internals
•   Reflection: http://java.sun.com/docs/books/tutorial/reflect/TOC.html
    http://tutorials.jenkov.com/java-reflection/index.html
Thank You!
  Questions?

More Related Content

What's hot

iOS Multithreading
iOS MultithreadingiOS Multithreading
iOS MultithreadingRicha Jain
 
Beyond JVM - YOW! Sydney 2013
Beyond JVM - YOW! Sydney 2013Beyond JVM - YOW! Sydney 2013
Beyond JVM - YOW! Sydney 2013Charles Nutter
 
[JavaOne 2011] Models for Concurrent Programming
[JavaOne 2011] Models for Concurrent Programming[JavaOne 2011] Models for Concurrent Programming
[JavaOne 2011] Models for Concurrent ProgrammingTobias Lindaaker
 
First fare 2011 frc-java-introduction
First fare 2011 frc-java-introductionFirst fare 2011 frc-java-introduction
First fare 2011 frc-java-introductionOregon FIRST Robotics
 
Java Garbage Collection, Monitoring, and Tuning
Java Garbage Collection, Monitoring, and TuningJava Garbage Collection, Monitoring, and Tuning
Java Garbage Collection, Monitoring, and TuningCarol McDonald
 
Java Course 9: Networking and Reflection
Java Course 9: Networking and ReflectionJava Course 9: Networking and Reflection
Java Course 9: Networking and ReflectionAnton Keks
 
Intro to Python (High School) Unit #2
Intro to Python (High School) Unit #2Intro to Python (High School) Unit #2
Intro to Python (High School) Unit #2Jay Coskey
 
Java session13
Java session13Java session13
Java session13Niit Care
 
IAP09 CUDA@MIT 6.963 - Guest Lecture: Out-of-Core Programming with NVIDIA's C...
IAP09 CUDA@MIT 6.963 - Guest Lecture: Out-of-Core Programming with NVIDIA's C...IAP09 CUDA@MIT 6.963 - Guest Lecture: Out-of-Core Programming with NVIDIA's C...
IAP09 CUDA@MIT 6.963 - Guest Lecture: Out-of-Core Programming with NVIDIA's C...npinto
 
Dojo for programmers (TXJS 2010)
Dojo for programmers (TXJS 2010)Dojo for programmers (TXJS 2010)
Dojo for programmers (TXJS 2010)Eugene Lazutkin
 
Grand Central Dispatch Design Patterns
Grand Central Dispatch Design PatternsGrand Central Dispatch Design Patterns
Grand Central Dispatch Design PatternsRobert Brown
 
Grand Central Dispatch
Grand Central DispatchGrand Central Dispatch
Grand Central Dispatchcqtt191
 
Pune-Cocoa: Blocks and GCD
Pune-Cocoa: Blocks and GCDPune-Cocoa: Blocks and GCD
Pune-Cocoa: Blocks and GCDPrashant Rane
 
Multithreading and Parallelism on iOS [MobOS 2013]
 Multithreading and Parallelism on iOS [MobOS 2013] Multithreading and Parallelism on iOS [MobOS 2013]
Multithreading and Parallelism on iOS [MobOS 2013]Kuba Břečka
 
Effective java - concurrency
Effective java - concurrencyEffective java - concurrency
Effective java - concurrencyfeng lee
 

What's hot (20)

iOS Multithreading
iOS MultithreadingiOS Multithreading
iOS Multithreading
 
Beyond JVM - YOW! Sydney 2013
Beyond JVM - YOW! Sydney 2013Beyond JVM - YOW! Sydney 2013
Beyond JVM - YOW! Sydney 2013
 
[JavaOne 2011] Models for Concurrent Programming
[JavaOne 2011] Models for Concurrent Programming[JavaOne 2011] Models for Concurrent Programming
[JavaOne 2011] Models for Concurrent Programming
 
First fare 2011 frc-java-introduction
First fare 2011 frc-java-introductionFirst fare 2011 frc-java-introduction
First fare 2011 frc-java-introduction
 
Java Garbage Collection, Monitoring, and Tuning
Java Garbage Collection, Monitoring, and TuningJava Garbage Collection, Monitoring, and Tuning
Java Garbage Collection, Monitoring, and Tuning
 
Java Course 9: Networking and Reflection
Java Course 9: Networking and ReflectionJava Course 9: Networking and Reflection
Java Course 9: Networking and Reflection
 
Intro to Python (High School) Unit #2
Intro to Python (High School) Unit #2Intro to Python (High School) Unit #2
Intro to Python (High School) Unit #2
 
Chapter08
Chapter08Chapter08
Chapter08
 
Java session13
Java session13Java session13
Java session13
 
IAP09 CUDA@MIT 6.963 - Guest Lecture: Out-of-Core Programming with NVIDIA's C...
IAP09 CUDA@MIT 6.963 - Guest Lecture: Out-of-Core Programming with NVIDIA's C...IAP09 CUDA@MIT 6.963 - Guest Lecture: Out-of-Core Programming with NVIDIA's C...
IAP09 CUDA@MIT 6.963 - Guest Lecture: Out-of-Core Programming with NVIDIA's C...
 
Dojo for programmers (TXJS 2010)
Dojo for programmers (TXJS 2010)Dojo for programmers (TXJS 2010)
Dojo for programmers (TXJS 2010)
 
Grand Central Dispatch Design Patterns
Grand Central Dispatch Design PatternsGrand Central Dispatch Design Patterns
Grand Central Dispatch Design Patterns
 
Grand Central Dispatch
Grand Central DispatchGrand Central Dispatch
Grand Central Dispatch
 
hibernate
hibernatehibernate
hibernate
 
Guild Prototype
Guild PrototypeGuild Prototype
Guild Prototype
 
04 - Qt Data
04 - Qt Data04 - Qt Data
04 - Qt Data
 
Pune-Cocoa: Blocks and GCD
Pune-Cocoa: Blocks and GCDPune-Cocoa: Blocks and GCD
Pune-Cocoa: Blocks and GCD
 
Multithreading and Parallelism on iOS [MobOS 2013]
 Multithreading and Parallelism on iOS [MobOS 2013] Multithreading and Parallelism on iOS [MobOS 2013]
Multithreading and Parallelism on iOS [MobOS 2013]
 
Effective java - concurrency
Effective java - concurrencyEffective java - concurrency
Effective java - concurrency
 
QtQuick Day 3
QtQuick Day 3QtQuick Day 3
QtQuick Day 3
 

Similar to Vk.amberfog.com gtug part1_introduction2_javaandroid_gtug

Memory Analysis of the Dalvik (Android) Virtual Machine
Memory Analysis of the Dalvik (Android) Virtual MachineMemory Analysis of the Dalvik (Android) Virtual Machine
Memory Analysis of the Dalvik (Android) Virtual MachineAndrew Case
 
GOTO Night with Charles Nutter Slides
GOTO Night with Charles Nutter SlidesGOTO Night with Charles Nutter Slides
GOTO Night with Charles Nutter SlidesAlexandra Masterson
 
Basic info on java intro
Basic info on java introBasic info on java intro
Basic info on java introkabirmahlotra
 
Basic info on java intro
Basic info on java introBasic info on java intro
Basic info on java introkabirmahlotra
 
Clojure made-simple - John Stevenson
Clojure made-simple - John StevensonClojure made-simple - John Stevenson
Clojure made-simple - John StevensonJAX London
 
Java Future S Ritter
Java Future S RitterJava Future S Ritter
Java Future S Rittercatherinewall
 
2013.02.02 지앤선 테크니컬 세미나 - Xcode를 활용한 디버깅 팁(OSXDEV)
2013.02.02 지앤선 테크니컬 세미나 - Xcode를 활용한 디버깅 팁(OSXDEV)2013.02.02 지앤선 테크니컬 세미나 - Xcode를 활용한 디버깅 팁(OSXDEV)
2013.02.02 지앤선 테크니컬 세미나 - Xcode를 활용한 디버깅 팁(OSXDEV)JiandSon
 
JavaOne 2012 - JVM JIT for Dummies
JavaOne 2012 - JVM JIT for DummiesJavaOne 2012 - JVM JIT for Dummies
JavaOne 2012 - JVM JIT for DummiesCharles Nutter
 
Blocks & GCD
Blocks & GCDBlocks & GCD
Blocks & GCDrsebbe
 
Exploring Java Heap Dumps (Oracle Code One 2018)
Exploring Java Heap Dumps (Oracle Code One 2018)Exploring Java Heap Dumps (Oracle Code One 2018)
Exploring Java Heap Dumps (Oracle Code One 2018)Ryan Cuprak
 
An Introduction to JVM Internals and Garbage Collection in Java
An Introduction to JVM Internals and Garbage Collection in JavaAn Introduction to JVM Internals and Garbage Collection in Java
An Introduction to JVM Internals and Garbage Collection in JavaAbhishek Asthana
 
Using the Android Native Development Kit (NDK)
Using the Android Native Development Kit (NDK)Using the Android Native Development Kit (NDK)
Using the Android Native Development Kit (NDK)DroidConTLV
 
Building High Performance Android Applications in Java and C++
Building High Performance Android Applications in Java and C++Building High Performance Android Applications in Java and C++
Building High Performance Android Applications in Java and C++Kenneth Geisshirt
 
Scala at HUJI PL Seminar 2008
Scala at HUJI PL Seminar 2008Scala at HUJI PL Seminar 2008
Scala at HUJI PL Seminar 2008Yardena Meymann
 
Native code in Android applications
Native code in Android applicationsNative code in Android applications
Native code in Android applicationsDmitry Matyukhin
 

Similar to Vk.amberfog.com gtug part1_introduction2_javaandroid_gtug (20)

Memory Analysis of the Dalvik (Android) Virtual Machine
Memory Analysis of the Dalvik (Android) Virtual MachineMemory Analysis of the Dalvik (Android) Virtual Machine
Memory Analysis of the Dalvik (Android) Virtual Machine
 
GOTO Night with Charles Nutter Slides
GOTO Night with Charles Nutter SlidesGOTO Night with Charles Nutter Slides
GOTO Night with Charles Nutter Slides
 
Basic info on java intro
Basic info on java introBasic info on java intro
Basic info on java intro
 
Basic info on java intro
Basic info on java introBasic info on java intro
Basic info on java intro
 
Jvm internals
Jvm internalsJvm internals
Jvm internals
 
core java
core javacore java
core java
 
Clojure made-simple - John Stevenson
Clojure made-simple - John StevensonClojure made-simple - John Stevenson
Clojure made-simple - John Stevenson
 
Java Future S Ritter
Java Future S RitterJava Future S Ritter
Java Future S Ritter
 
2013.02.02 지앤선 테크니컬 세미나 - Xcode를 활용한 디버깅 팁(OSXDEV)
2013.02.02 지앤선 테크니컬 세미나 - Xcode를 활용한 디버깅 팁(OSXDEV)2013.02.02 지앤선 테크니컬 세미나 - Xcode를 활용한 디버깅 팁(OSXDEV)
2013.02.02 지앤선 테크니컬 세미나 - Xcode를 활용한 디버깅 팁(OSXDEV)
 
JavaOne 2012 - JVM JIT for Dummies
JavaOne 2012 - JVM JIT for DummiesJavaOne 2012 - JVM JIT for Dummies
JavaOne 2012 - JVM JIT for Dummies
 
Blocks & GCD
Blocks & GCDBlocks & GCD
Blocks & GCD
 
Understanding the Dalvik Virtual Machine
Understanding the Dalvik Virtual MachineUnderstanding the Dalvik Virtual Machine
Understanding the Dalvik Virtual Machine
 
Exploring Java Heap Dumps (Oracle Code One 2018)
Exploring Java Heap Dumps (Oracle Code One 2018)Exploring Java Heap Dumps (Oracle Code One 2018)
Exploring Java Heap Dumps (Oracle Code One 2018)
 
An Introduction to JVM Internals and Garbage Collection in Java
An Introduction to JVM Internals and Garbage Collection in JavaAn Introduction to JVM Internals and Garbage Collection in Java
An Introduction to JVM Internals and Garbage Collection in Java
 
java training faridabad
java training faridabadjava training faridabad
java training faridabad
 
Using the Android Native Development Kit (NDK)
Using the Android Native Development Kit (NDK)Using the Android Native Development Kit (NDK)
Using the Android Native Development Kit (NDK)
 
Building High Performance Android Applications in Java and C++
Building High Performance Android Applications in Java and C++Building High Performance Android Applications in Java and C++
Building High Performance Android Applications in Java and C++
 
Scala at HUJI PL Seminar 2008
Scala at HUJI PL Seminar 2008Scala at HUJI PL Seminar 2008
Scala at HUJI PL Seminar 2008
 
C# basics
C# basicsC# basics
C# basics
 
Native code in Android applications
Native code in Android applicationsNative code in Android applications
Native code in Android applications
 

Recently uploaded

DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 

Recently uploaded (20)

DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 

Vk.amberfog.com gtug part1_introduction2_javaandroid_gtug

  • 1. Introduction (part I): Java and Android basics Alexey Golubev, Dmitry Lukashev
  • 2. What is the plan? Java +Android Android UI Android in Action (basics) Layouts, ListView, Screen rotation, JVM, GC, Threads, Memory analyze, SDK, NDK, Activity, Menu, Dialog, Widgets, Tips & tricks, etc. AIDL, SAX, Debug, Code style, etc. Wakelock, etc. Part I Part II Part III
  • 3. Part I: Introduction What is this about? • Introduction to Java world • JVM, Dalvik VM, JIT • GC, multithreading, collections, etc. • Android Basics • Architecture • Building blocks, SDK, NDK, etc. • NDK demo
  • 4. Java overview • Sun VM, Dalvik VM, JIT • Garbage collection • References • Exceptions • Threads • Synchronization • Collections • Wrapper classes • Java and Android code style
  • 5. Where to start • http://developer.android.com/ • http://source.android.com/ • http://android.git.kernel.org/ • http://android-developers.blogspot.com/
  • 6. Java overview • Sun VM, Dalvik VM, JIT • Garbage collection • References • Exceptions • Threads • Synchronization • Collections • Wrapper classes • Java and Android code style
  • 7. JVM Class loader class files subsystem The pc register (program counter) Thread JVM Stack Native methods stacks Heap VM Method Area Сlass Runtime Constant Pool native Execution Native method method engine interface libraries
  • 8. Dalvik VM • Was written by Dan Bornstein • Transform class files into DEX • It is VM… – integrated with Linux – uses shared memory, mmap – for OS without swap space – while powered by a battery – zygote • The Dalvik VM is register-based: fewer instructions, code units, instructions • Verification & optimization at Give me your huddled bytecodes installation time yearning to run free. And I lift the light beside the coder’s door
  • 9. DEX file – shared constant pool .jar file .class file heterogeneous .dex file constant pool string_ids “Hello World” constant pool “Lcom/data/Data” other data type_ids int constant pool String[ ] .class file proto_ids String fn() heterogeneous constant pool void fn(int) constant pool field_ids String.offset constant pool Integer.MAX_VALUE other data method_ids PrintStream.println(…) constant pool Collection.size() .class file heterogeneous other data constant pool other data
  • 10. DEX file – memory saving • minimal repetition • per-type pools (implicit typing) • implicit labeling common system libraries (U) 21445320 — 100% (uncompressed jar file) (J) 10662048 — 50% (compressed jar file) (D) 10311972 — 48% (uncompressed dex file) web browser app (U) 470312 — 100% (J) 232065 — 49% (D) 209248 — 44% • Google claims that Dalvik bytecode is more efficient than Sun’s stack bytecode
  • 11. JIT (since Android 2.2) • Translates byte code to optimized native code at run time • Part of the open source • Trace JIT vs Method JIT • Trace JIT – Minimizing memory usage critical for mobile devices (100K) – Important to deliver performance boost quickly – Trace request is built during interpretation – Compiled traces chained together in translation cache – Per process translation cache • Leave open the possibility of supplementing with method- based JIT
  • 12. Java overview • Sun VM, Dalvik VM, JIT • Garbage collection • References • Exceptions • Threads • Synchronization • Collections • Wrapper classes • Java and Android code style
  • 13. Garbage collection • GC is under control of the JVM • An object is eligible for garbage i2 The heap collection when no live thread can access it i3 i2.n • System.gc(); i4 Runtime.getRuntime().gc() • static – variables with the longest life time i3.n i4.n public class Island { Island i; public static void main(String[] args) { Island i2 = new Island(); Island i3 = new Island(); Island i4 = new Island(); “Islands of Isolation” i2.n = i3; i3.n = i4; i4.n = i2; x i2 = null; i3 = null; i4 = null; Island x = new Island(); x = null; } }
  • 14. Mark and Sweep example • Obtain locks and suspend threads Parallel mark bits in Dalvik VM (separate from • Mark phase other heap memory) – Process of identifying all objects reachable from the root set. – All “live” objects are marked by setting a mark bit in the mark bit vector. • Sweep phase – Sweep phase identifies all the objects that have been allocated, but no longer referenced. • Compaction (optional) – Once garbage has been removed, we consider compacting the resulting set of objects to remove spaces between them. • Release locks and resume threads
  • 15. Generational GC • Most recently created objects – most likely to become unreachable quickly Young Generation Old Generation • Minor Collection – takes place only in the young generation, normally done through direct copying – very efficient • Major Collection – takes place in the new and old generation and uses the normal mark/sweep (+compact) algorithm
  • 16. Strings • Strings are immutable in Java String x = “Hi"; String s1 = "abc"; // 1 object, 1 reference String s2 = "abc"; The heap // s1 == s2 String s3 = new String("abc"); // 2 “Hi” objects, 1 reference x String s4 = new String("abc"); // s3 != s4 // optimization by interning strings x = x.concat(" GTUG!"); s3 = s3.intern(); s4 = s4.intern(); The heap • Use StringBuffer, StringBuilder “Hi” • Set initial capacity of StringBuilder x “Hi GTUG”
  • 17. Quiz class Foo { int[] mArray = { 1, 2, 3, 4, 5 }; } [ ref0, ref1, ref2] public class Test { public static void main(String[] args) { Foo[] fa = new Foo[3]; Foo() [] fa[0] = new Foo(); Foo f = new Foo(); Foo() [] fa[1] = f; f = null; fa[1] = null; // how many objects were created at this point? // how many are eligible for gc()? } }
  • 18. Performance • Do not allocate memory as much as you can • GC is slow (~x00 ms on Android device) • Decrease number of objects – GC will work faster (i.e. StringBuffer vs String) • Use primitive types for arrays (int vs Integer) • Use special methods: String.indexOf(), substring(), etc. • Use exact class types instead of interfaces (i.e. HashMap instead of Map) on devices without JIT • Use static where possible ArrayList<MyClass> mList = new • Avoid internal getters/setters ArrayList<MyClass>(); ... • Use enhanced for-loop syntax for (MyClass next : mList) { ... }
  • 19. Java overview • Sun VM, Dalvik VM, JIT • Garbage collection • References • Exceptions • Threads • Synchronization • Collections • Wrapper classes • Java and Android code style
  • 20. References • Strong reference: Object obj = new Object(); • SoftReference – soft references will be cleared before the JVM reports an out-of-memory condition (memory-sensitive cache) • WeakReference – gc frees weakly reachable object when it founds it, avoid memory leaks (e.g. http://en.wikipedia.org/wiki/Flyweight_pattern) • PhantomReference – is useful only to track the impending collection of the referring object. Must be used only with the ReferenceQueue class. Most often used for scheduling pre- mortem cleanup actions in a more flexible way than is possible with the Java finalization mechanism
  • 21. SoftReference: simple cache private final HashMap<String, SoftReference<T>> mCache; public put(String key, T value) { mCache.put(key, new SoftReference<T>(value)); } public T get(String key, ValueBuilder builder) { T value = null; SoftReference<T> reference = mCache.get(key); if (reference != null) { value = reference.get(); } // Not in cache or gc'd if (value == null) { value = builder.build(key); mCache.put(key, new SoftReference<T>(value)); } return value; }
  • 22. git://android.git.kernel.org/platform/packages/apps/Mms.git/src/com/android/mms/model/ImageModel.java package com.android.mms.model; public class ImageModel extends RegionMediaModel { private static final String TAG = "Mms/image"; private static final int THUMBNAIL_BOUNDS_LIMIT = 480; private SoftReference<Bitmap> mBitmapCache = new SoftReference<Bitmap>(null); ... private Bitmap internalGetBitmap(Uri uri) { Bitmap bm = mBitmapCache.get(); if (bm == null) { try { bm = createThumbnailBitmap(THUMBNAIL_BOUNDS_LIMIT, uri); if (bm != null) { mBitmapCache = new SoftReference<Bitmap>(bm); } } catch (OutOfMemoryError ex) { // fall through and return a null bitmap. // The callers can handle a null // result and show R.drawable.ic_missing_thumbnail_picture } } return bm; } SoftReference }
  • 23. git://android.git.kernel.org/platform/frameworks/base.git/core/java/android/app/Dialog.java package android.app; public class Dialog implements DialogInterface, Window.Callback, KeyEvent.Callback, OnCreateContextMenuListener { ... private static final class ListenersHandler extends Handler { private WeakReference<DialogInterface> mDialog; public ListenersHandler(Dialog dialog) { mDialog = new WeakReference<DialogInterface>(dialog); } @Override public void handleMessage(Message msg) { switch (msg.what) { case DISMISS: ((OnDismissListener) msg.obj).onDismiss(mDialog.get()); break; case CANCEL: ((OnCancelListener) msg.obj).onCancel(mDialog.get()); break; case SHOW: ((OnShowListener) msg.obj).onShow(mDialog.get()); break; } } } WeakReference }
  • 24. finalize() • The finalize() method is guaranteed to run once and only once before GC deletes an object • GC makes no guarantees, finalize() may never run • You can uneligibilize an object for GC within finalize() • Do not use it for resource closing
  • 25. Java overview • Sun VM, Dalvik VM, JIT • Garbage collection • References • Exceptions • Threads • Synchronization • Collections • Wrapper classes • Java and Android code style
  • 26. Exceptions try { // do stuff Object } catch (SomeException e) { // do exception handling } finally { // clean up Throwable } try { // do stuff } finally { Error Exception // clean up } AssertionError RuntimeException StackOverflowError OutOfMemoryError NullPointerException IndexOfBoundException IOException SQLiteException
  • 27. try/catch/finally (1) class Test { private String data = "test"; private int test() { try { System.out.println(data.length()); return 0; } catch (NullPointerException e) { 4 System.out.println("exception"); return 1; finally } finally { result = 2 System.out.println("finally"); return 2; } } public static void main(String[] args) { Test t = new Test(); System.out.println("result = " + t.test()); } }
  • 28. try/catch/finally (2) class Test { private String data; private int test() { try { System.out.println(data.length()); return 0; } catch (NullPointerException e) { exception System.out.println("exception"); return 1; finally } finally { result = 2 System.out.println("finally"); return 2; } } public static void main(String[] args) { Test t = new Test(); System.out.println("result = " + t.test()); } }
  • 29. DefaultExceptionHandler public class DefaultExceptionHandler implements UncaughtExceptionHandler { private UncaughtExceptionHandler mDefaultExceptionHandler; public DefaultExceptionHandler(UncaughtExceptionHandler pDefaultExceptionHandler) { mDefaultExceptionHandler = pDefaultExceptionHandler; } public void uncaughtException(Thread t, Throwable e) { mDefaultExceptionHandler.uncaughtException(t, e); t.getThreadGroup().destroy(); } } Thread.setDefaultUncaughtExceptionHandler(new DefaultExceptionHandler(Thread.getDefaultUncaughtExceptionHandler()));
  • 30. Java overview • Sun VM, Dalvik VM, JIT • Garbage collection • References • Exceptions • Threads • Synchronization • Collections • Wrapper classes • Java and Android code style
  • 31. Threads • When it comes to threads, very little is guaranteed • Create thread: extend java.lang.Thread or implement Runnable interface • A thread is done being a thread when its target run() method completes • Once a thread has been started, it can never be started again • The order in which runnable threads are chosen is not guaranteed • sleep(long ms), yield(), join(), setPriority(int priority), wait(), notify(), notifyAll()
  • 32. Thread states Waiting/ blocking wait, sleep, join, lock yield New Runnable Running Dead start() run() completes not alive alive not alive
  • 33. Java overview • Sun VM, Dalvik VM, JIT • Garbage collection • References • Exceptions • Threads • Synchronization • Collections • Wrapper classes • Java and Android code style
  • 34. Synchronization • Every Object in java has build-in lock • Only methods or blocks can be synchronized public static synchronized int getCount() { return count; } public static int getCount() { synchronized(MyClass.class) { // Class c = Class.forName(“MyClass”); return count; } } • notify(), join(), sleep(), yield() keep locks, wait() gives up lock • synchronized keyword is not automatically inherited when subclasses override superclass method
  • 35. Volatile public class Task extends Thread { class VolatileExample { private volatile boolean mIsStop; int x = 0; volatile boolean v = false; public void run() { public void writer() { while (!mIsStop) { x = 42; // do some stuff... v = true; } } } public void reader() { if (v == true) { public void stopMe() { // uses x - guaranteed to see 42. mIsStop = true; } } } } } volatile: • Every thread accessing the field will read its current value before continuing, instead of (potentially) using a cached value • Statements accessing the variable will be executed in the order they are written (Java 5 or later)
  • 36. Singleton pattern example (1) public class Singleton { private static final Singleton INSTANCE = new Singleton(); private Singleton() {} public static Singleton getInstance() { return INSTANCE; } thread-safe } public class Singleton { private static Singleton sInstance; private Singleton() {} public static Singleton getInstance() { if (sInstance == null) { sInstance = new Singleton(); } return sInstance; lazy init } } non-thread-safe
  • 37. Singleton pattern example (2) public class Singleton { private static Singleton sInstance; private Singleton() {} public synchronized static Singleton getInstance() { if (sInstance == null) { sInstance = new Singleton(); } lazy init return sInstance; thread-safe } } low performance
  • 38. Singleton pattern example (3) public class Singleton { private static Singleton sInstance; private Singleton() {} public static Singleton getInstance() { if (sInstance == null) { synchronized (Singleton.class) { if (sInstance == null) { // “Double-Checked Locking” idiom sInstance = new Singleton(); } } } return sInstance; } }
  • 39. Singleton pattern example (4) public class Singleton { private volatile static Singleton sInstance; private Singleton() {} public static Singleton getInstance() { if (sInstance == null) { synchronized (Singleton.class) { if (sInstance == null) { sInstance = new Singleton(); } } } return sInstance; } } lazy init & thread-safe (Java 5 or later)
  • 40. Singleton pattern example (5) public class Singleton { private Singleton() {} private static class SingletonHolder { private static final Singleton INSTANCE = new Singleton(); } public static Singleton getInstance() { return SingletonHolder.INSTANCE; } } lazy init & thread-safe (for all Java version)
  • 41. Quiz public class Foo { private static final int DELTA = 6; private static Foo sInstance = new Foo(); private static int sBase = 7; private int mX; private Foo() { mX = sBase + DELTA; } public static void main(String[] args) { System.out.println(Foo.sInstance.mX); } } What is the print? 6
  • 42. Java overview • Sun VM, Dalvik VM, JIT • Garbage collection • References • Exceptions • Threads • Synchronization • Collections • Wrapper classes • Java and Android code style
  • 43. Collection Collections Set List Queue HashSet SortedSet LinkedHashSet NavigableSet ArrayList Vector LinkedList PriorityQueue 1.6 TreeSet Map SortedMap WeakHashMap ConcurrentHashMap CopyOnWriteArraySet HashTable HashMap NavigableMap 1.6 etc… LinkedHashMap TreeMap
  • 44. Hash table • Choosing a good hash function • Collision resolution: separate chaining, open addressing • Load factor Key Hashcode Algorithm Hashcode 19 Bob 19 Bob Alex A(1)+L(12)+E(5)+X(24) 42 33 Fred 33 Fred Bob B(2)+O(15)+B(2) 19 42 Alex Dirk 42 Alex Dirk D(4)+I(9)+R(18)+K(11) 42 43 Dirk Fred F(6)+R(18)+E(5)+D(4) 33 • Find the right bucket (using hashCode()) • Search the bucket for the right element (using equals())
  • 45. Contracts The equals() contract • Reflexive – x.equals(x)=true • Symmetric – x.equals(y)=true -> y.equals(x)=true • Transitive – x.equals(y)=true, y.equals(z)=true -> x.equals(z)=true • Consistent – multiple invocations • x.equals(null)=false The hashCode() contract @Override • Consistent during the app execution public int hashCode() { return 1; • If x.equals(y) -> hash must be the same }
  • 46. Java overview • Sun VM, Dalvik VM, JIT • Garbage collection • References • Exceptions • Threads int • Synchronization • Collections • Wrapper classes • Java and Android code style
  • 47. Wrapper Classes and Boxing (1) • The wrapper classes correlate to primitive types • Wrappers have two main functions: – To wrap primitives so that they can be handled like objects – To provide utility methods for primitives (conversions) • Wrapper constructors can take String (except Character) • As of Java 5, boxing allows to convert primitives to wrappers or vice versa automatically. Integer x = 100; x++; int x2 = x.intValue(); x2++; x = new Integer(x2);
  • 48. Wrapper Classes and Boxing (2) Integer i1 = 1000; Integer i2 = 1000; if (i1 != i2) System.out.println("i1!=i2"); i1!=i2 if (i1 == i2) System.out.println("i1==i2"); Integer i1 = 100; Integer i2 = 100; if (i1 != i2) System.out.println("i1!=i2"); I1==i2 if (i1 == i2) System.out.println("i1==i2"); JVM saves memory for: • Boolean • Byte • Character from u0000 to u007f • Short and Integer from -128 to 127
  • 49. Java overview • Sun VM, Dalvik VM, JIT • Garbage collection • References • Exceptions • Threads • Synchronization • Collections • Wrapper classes • Java and Android code style
  • 50. Java Code Style: why? • 80% of the lifetime cost of a piece of software goes to maintenance • Hardly any software is maintained for its whole life by the original author • Code conventions improve the readability of the software, allowing engineers to understand new code more quickly and thoroughly • Makes it easier to conduct code reviews http://developers.sun.com/sunstudio/products/archive/whitepapers/java-style.pdf
  • 51. Comments, TODOs, etc. • Comments • TODO, FIXME, XXX – Use TODO comments for code that is temporary, a short- term solution, or good-enough but not perfect. • Copyrights
  • 52. Android Code Style (1) • Import ordering – Android imports – Imports from third parties (com, junit, net, org) – java and javax • Indentation – We use 4 space indents for blocks. We never use tabs. When in doubt, be consistent with code around you – We use 8 space indents for line wraps, including function calls and assignments • Field Names – Non-public, non-static field names start with m. – Static field names start with s. – Other fields start with a lower case letter. – Public static final fields (constants) are ALL_CAPS_WITH_UNDERSCORES.
  • 53. Android Code Style (2) • Braces – Braces do not go on their own line; they go on the same line as the code before them if (condition) { body; // ok } if (condition) body; // ok - 1 line if (condition) body; // bad • Line length – Each line of text in your code should be at most 100 characters long. • Annotations, Logging http://source.android.com/submit-patches/code-style-guide
  • 54. BAD Code Style sample (1) for(int i=0;i<amount;++i) db.execSQL(sqls[i]); public static final int sMaxSQLsInTransaction= 1000; if (delayed == true) { ... } else { ... } Good: XmlHttpRequest getCustomerId class Html long id Bad: XMLHTTPRequest getCustomerID class HTML long ID
  • 55. BAD Code Style sample (2) public static final boolean PushValues(String pattern, ArrayList<Integer> patternIds,/*OUT */ArrayList<String> values) { int idsAmount= (null != patternIds ? patternIds.size() : 0); if(0<idsAmount){ final int patternLen=(null!=pattern ? pattern.length():0); if(0<patternLen){ for(int i=0; i<idsAmount; ++i){ if(!pushValues(pattern,patternLen,patternIds.get(i),values)){ return (false); } } return (true); } } return (false); }
  • 56. BAD Code Style sample (2) public static final ArrayList<String> getValues(final String pattern, final ArrayList<Integer> patternIds) { ArrayList<Integer> result = new ArrayList<Integer>(); if (pattern != null && pattern.length() > 0 && patternIds != null) { for (int patternId : patternIds) { ArrayList<Integer> values = getValuesForPatternId(pattern, patternId); if (values == null) { return null; } result.addAll(values); } } return result; }
  • 57. Let’s Have a Break! 10 min
  • 58. Android basics • Architecture Overview • Building Blocks • Manifest • System Services • Platform versions • Saving Application State • NDK • Make your code better
  • 59. Android • Architecture Overview • Building Blocks • Manifest • System Services • Platform versions • Saving Application State • NDK • Make your code better
  • 60. Android History • Jul 2005 – Google acquired Android Inc. (co-founded by Andy Rubin) • Nov 2007 – Google Android presentation and “early look” release Sep 2008 Éclair Mar May Sep Oct Dec 1.0 2009 2009 2009 2009 2009 Froyo Jan May 1.1 1.5 1.6 2.0 2.0.1 2010 2010 2.1 2.2 Cupcake Donut Gingerbread
  • 61. Android Architecture Overview Applications Home Contacts Phone Browser … Application Framework NDK / JNI Activity Manager Window Manager Content Providers View System Resource Manager Package Manager Telephony Manager Notification Manager Location Manager Libraries Android Runtime Surface Manager Media Framework SQLite Core Libraries OpenGL | ES FreeType WebKit Dalvik VM SGL SSL libc Linux Kernel Display Driver Camera Driver Flash Memory Driver Binder (IPC) Driver Keypad Driver WiFi Driver Audio Drivers Power Management
  • 62. Android • Architecture Overview • Building Blocks • Manifest • System Services • Platform versions • Saving Application State • NDK • Make your code better
  • 63. Android Application Building Blocks • Activity – Presents UI – Each Activity is independent screen – Activity: setContentView(View) • Service – Used for background operations • BroadcastReceiver – Receive and process broadcast system or user events • ContentProvider – Share application data with others – Data can be stored in FS, DB or even in memory – Communicate via ContentResolver • Intent – Used to activate Activities, Services & BroadcastReceivers http://developer.android.com/guide/topics/fundamentals.html
  • 64. Android Application • Controls global Application state • Extend Application class (android.app.Application) – onCreate() – onLowMemory() – onTerminate() – getApplicationContext() – to use it in classes, where is no Context • Point custom Application class in AndroidManifest.xml
  • 65. Android Context Application Context Activity Context • Non UI Context • Same as for Application, but specific • startActivity(Intent) to current Activity • start /stopService(Intent) • startActivityForResult(Intent) / • sendBroadcast(Intent) finish() • register / unregisterReciever() • bindService(Intent) • Application FS, Preferences, • UI: setContentView(View), Resources findViewById() • getSystemService • User events handling (Keys, Touches, Trackball)
  • 66. Android • Architecture Overview • Building Blocks • Manifest • System Services • Platform versions • Saving Application State • NDK • Make your code better
  • 67. AndroidManifest.xml (1) <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.my.example" android:versionName="1.0 beta" android:versionCode="2"> <application android:name=".MyApplication" android:label="..." android:icon="..."> <activity android:name=".MyActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.DEFAULT" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <service ... /> <receiver ... /> <provider ... /> </application> </manifest>
  • 68. AndroidManifest.xml (2) <activity android:name=".MyActivity" android:launchMode="singleTask" android:theme="@style/Theme.MyDialog" /> <service android:name=".MyService" android:process="new"/> <receiver android:name=".MyReceiver" > <intent-filter> <action android:name= "android.intent.action.PACKAGE_REMOVED" /> <category android:name= "android.intent.category.DEFAULT" /> <data android:scheme= "package" /> </intent-filter> </receiver> <provider android:name=".MyProvider" android:authorities="com.my.provider" />
  • 69. AndroidManifest.xml (3) <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="..." package="com.my.example" android:versionName="1.0 beta" android:versionCode="2"> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.BLUETOOTH" /> <uses-sdk android:minSdkVersion="3" android:targetSdkVersion="4"/> <supports-screens android:largeScreens="true" android:normalScreens="true" android:smallScreens="true" android:resizeable="true" android:anyDensity="true" /> <application ...> ... </application> </manifest>
  • 70. AndroidManifest.xml (4) <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="..." package="com.my.example" android:versionName="1.0 beta" android:versionCode="2"> <uses-configuration android:reqHardKeyboard="true" android:reqTouchScreen="true" /> <uses-feature android:name="android.software.live_wallpaper" /> <uses-feature android:name="android.hardware.telephony" /> <uses-feature android:name="android.hardware.telephony.cdma" /> ... </manifest>
  • 71. Android • Architecture Overview • Building Blocks • Manifest • System Services • Platform versions • Saving Application State • NDK • Make your code better
  • 72. Android System Services Object getApplicationContext().getSystemService(String serviceName) serviceName value Service Class name Description (contsants in Context) WINDOW_SERVICE WindowManager Controls on-screen windows and their parameters LAYOUT_INFLATER_SERVICE LayoutInflater Inflates layout resources POWER_SERVICE PowerManager Controls power management NOTIFICATION_SERVICE NotificationManager Status bar notifications CONNECTIVITY_SERVICE ConnectivityManager Handling network connections WIFI_SERVICE WifiManager Handling Wi-Fi network status TELEPHONY_SERVICE TelephonyManager Handling phone calls states LOCATION_SERVICE LocationManager Controls location (GPS) updates SENSOR_SERVICE SensorManager Controls sensor … … …
  • 73. Android • Architecture Overview • Building Blocks • Manifest • System Services • Platform versions • Saving Application State • NDK • Make your code better
  • 74. Android Platform Versions • May 2009 – platform ver. 1.5 • May 2010 – platform ver. 2.2 • Six platform releases in a year (platform ver.1.1 is hard to find on real phones) • Platforms are back-compatible • It is good point to be compatible with dominated platforms (1.5, 1.6, 2.0.1 and 2.1) • To use advantages of the latest platform versions, Java Reflection mechanism should be used
  • 75. Android Platform Fragmentation in the World December 2009 June 2010
  • 76. Android Platform Fragmentation in Russia Android 2.2 ; 0,5% Android 2.0 ; 0,1% Android 2.0.1 ; 0,6% Android 1.6 ; 21,7% Android 1.5 ; 43,6% Android 2.1; 33,6% • Data gathered by Flurry service in real application • About 0.5% of 2.1 in Russia are custom ROMs
  • 77. Java Reflection • Originally used to inspect classes, interfaces, fields and methods at runtime, without knowing the names of them at compile time. It can be used for observing and/or modifying program execution at runtime • Classes: Class, Method, Field, Constructor, etc. // Without reflection Foo foo = new Foo(); foo.hello(); // With reflection Class cls = Class.forName("Foo"); Object foo = cls.newInstance(); Method method = cls.getMethod("hello", null); method.invoke(foo, null);
  • 78. Java Reflection and Android public class ClassHolder { private static NewClass foo; public static void tryNewClass() { foo = new NewClass(); } } try { ClassHolder.tryNewClass(); // NewClass available } catch (VerifyError e) {} try { Method methodName = ClassName.class.getMethod(...); methodName.invoke(Object obj, Object... args); } catch (NoSuchMethodException e) {} try { Field fieldName = ClassName.class.getField(...); fieldName.getType(Object obj); } catch (NoSuchFieldException e) {}
  • 79. Java Reflection and Android (Example) private static Field densityDpiField; private static Field densityDpiLowResValue; private static boolean sIsLowRes = false; private static boolean sIsNormalRes = true; static { try { densityDpiField = DisplayMetrics.class.getField("densityDpi"); densityDpiLowResValue = DisplayMetrics.class.getField("DENSITY_LOW"); } catch (NoSuchFieldException nfe) { // Old device - no density Field } }
  • 80. Java Reflection and Android (Example) (Cont.) static { if (densityDpiField != null) { DisplayMetrics dMetrics = sContext.getResources().getDisplayMetrics(); int densityDpi = 0; try { densityDpi = densityDpiField.getInt(dMetrics); sIsLowRes = (densityDpi == densityDpiLowResValue.getInt(dMetrics)); sIsNormalRes =(densityDpi==densityDpiMediumResValue.getInt(dMetrics)); } catch (Exception e) { sIsLowRes = false; sIsNormalRes = true; } } }
  • 81. Java Reflection and Android (Example) (Cont.) public static int scaleToDensity(int dp_size) { if (dp_size == 0 || sIsNormalRes) { return dp_size; } return (int)(dp_size * sContext.getResources().getDisplayMetrics().density + 0.5f); }
  • 82. Android • Architecture Overview • Building Blocks • Manifest • System Services • Platform versions • Saving Application State • NDK • Make your code better
  • 83. Saving State of Android Application • Shared Preferences are stored in the application private data space and can be shared only inside this Application, but between launches and versions • Instance of SharedPreferences class should be obtained: Activity.getPreferences() PreferenceManager.getDefaultSharedPreferences(Context ctx) Context.getSharedPreferences(String name, int mode) • To read: mPreferences.getType(String key, T defValue); • To write: SharedPreferences.Editor editor = mPreferences.edit(); editor.putType(String key, T value); editor.commit(); • SharedPreferences.OnSharedPreferenceChangeListener
  • 84. Backup Application Data (android.app.backup – 2.2) • Perform backup arbitrary data to remote “cloud” storage • Easily perform backup of SharedPreferences and files • Restore the data saved to remote storage • Controlled by Android Backup Manager – Extend class BackupAgent and override onBackup() & onRestore() OR – Extend BackupAgentHelper to backup/restore SharedPreferences and files from internal storage – Add your agent to AndroidManifest.xml <application android:backupAgent=".MyBackupAgent" > • BackupManager.dataChanged()/requestRestore() • New bmgr tool for testing http://developer.android.com/guide/developing/tools/bmgr.html • Full guide with examples: http://developer.android.com/guide/topics/data/backup.html
  • 85. Android • Architecture Overview • Building Blocks • Manifest • System Services • Platform versions • Saving Application State • NDK • Make your code better
  • 86. Android NDK (Native Development Kit) • Provides ability and tools to embed components that make use of native code in Android applications • Supports only restricted set of native libraries: – libc (C library) headers – libm (math library) headers – JNI interface headers – libz (Zlib compression) headers – liblog (Android logging) header – OpenGL ES 1.1 (since 1.6) and OpenGL ES 2.0 (3D graphics libraries, since 2.0) headers – libjnigraphics (Pixel buffer access) header (since 2.2) – A Minimal set of headers for C++ support • For Windows Cygwin 1.7 (or higher) is needed
  • 88. Android • Architecture Overview • Building Blocks • Manifest • System Services • Platform versions • Saving Application State • NDK • Make your code better
  • 89. Designing for Performance Action Time • Use final for constants Add a local variable 1 • Avoid enums Add a member variable 4 Call String.length() 5 • Avoid float Call empty static native method 5 • Use local variables for access to Call empty static method 12 Call empty virtual method 12.5 object fields inside loops (or more Call empty interface method 15 than once) Call Iterator:next() on a HashMap 165 • Don’t use private scope with Inner Call put() on a HashMap 600 Classes Inflate 1 View from XML 22,000 Inflate 1 LinearLayout containing 25,000 1 TextView Inflate 1 LinearLayout containing 135,000 6 TextView objects Launch an empty activity 3000,000
  • 90. Designing for Responsiveness • Application Not Responding (ANR) dialog: – No response to an input event (e.g. key press, screen touch) within 5 seconds – A BroadcastReceiver hasn't finished executing within 10 seconds • Quick Activity life-cycle methods (onCreate, onResume) and all other methods working on UI thread • Use new Thread for long-time operations (i.e. network/database operations, expensive computations, bitmap resizing, etc.) • Use ProgressBar or ProgressDialog to show “Loading…” or use splash screen when starting application • To avoid long-time operations in BroadcastReceiver – start Service (not Activity!)
  • 91. Designing for Seamlessness • React correctly on system events (i.e. phone call) • onSaveInstanceState/onResumeInstanceState • onPause/onResume • TelephonyManager, etc. • Share data using ContentProvider • Use NotificationManager and Notifications from background processes (Service, BroadcastReceiver) • Don’t overload a single Activity screen – use several Activities for correct dealing with history and Android “backstack” model • Use Threads for long-time operations to avoid ANR • Remember about multiple screen resolutions and multiple Android platform versions • Assume the Network is slow (change speed in Eclipse DDMS for Emulator) • Don’t assume Touchscreen or Keyboard • Remember about battery life
  • 93. Contacts Dmitry Lukashev http://ru.linkedin.com/in/dmitrylukashev dmitry.lukashev@gmail.com Alexey Golubev http://ru.linkedin.com/in/golubevalexey goalstudio@gmail.com Blog - http://android.amberfog.com/
  • 94. Future reading • http://developer.android.com/guide/index.html • http://developer.android.com/resources/index.html • Soft, weak, phantom references: http://www.ibm.com/developerworks/library/j- refs/ http://www.ibm.com/developerworks/java/library/j-jtp11225/index.html http://www.ibm.com/developerworks/java/library/j-jtp01246.html • JVM specification: http://java.sun.com/docs/books/jvms/second_edition/html/VMSpecTOC.doc.html • The Java Memory Model: http://www.cs.umd.edu/~pugh/java/memoryModel/ • Dalvik VM: http://sites.google.com/site/io/dalvik-vm-internals • Reflection: http://java.sun.com/docs/books/tutorial/reflect/TOC.html http://tutorials.jenkov.com/java-reflection/index.html
  • 95. Thank You! Questions?