Download - Advanced android
![Page 2: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/2.jpg)
Instructor
• Senior Software Engineer at Varonis
• Before worked for Samsung, Redbend and few start ups
• M.Sc. Computer Science and MBA in Marketing
• Android Related Stuff
– Author of Profiterole Big Data on Android http://code.google.com/p/profiterole/
– Key Member in Docomo Lock leading Android lock security application
http://www.nttdocomo.co.jp/english/service/safety/lock/
– P2P and Java compilations Android open projects participation (JXTA
http://code.google.com/p/peerdroid/ and ANTLR http://www.antlr.org/ )
– Analytics and Security for Redbend and Data Governance for Varonis
![Page 3: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/3.jpg)
Teaching
• Basic Android
• Advanced Java
• Big Data/Map Reduce
• Design Patterns
• API Design and Android Seminars
![Page 4: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/4.jpg)
This Seminar
• Understanding application architecture, its advantages and
limitations is really important for developing good applications.
• Existing descriptions of Android application architecture I have seen
so far are not very helpful.
• Android site provides a lot of how instead of what and why
• Stack Overflow/Blogs – content mining, digging checking
• Android sources – the best, but no time and capacity to understand
completely
![Page 5: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/5.jpg)
This seminar
• We are going to review Android Application Patterns and Practices Top Down approach
• These practices I used/collected over the years reviewing various Android projects usually via my or other mistakes I have seen
• We concentrate “on what and why” should be expected on each level
• In your work as Senior Developer/Architect will have a “check list” of what to expect
• No copy paste of APIs from Google
![Page 6: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/6.jpg)
This Seminar contd’
• We are going to touch various aspects at
very high level
– Lack of time
– I can’t cover everything
• We have to run on subjects
• Your participation/share is welcome !
![Page 7: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/7.jpg)
![Page 8: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/8.jpg)
When I get the APK
• I would like to check if the intellectual
property could be leaked
• It is very easy to disassemble APK as we
see in next slides
![Page 9: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/9.jpg)
2 directions to disassemble
• Access to source code (we cover now)
– Intellectual property
– Trade secrets
• Post Compile Injection (out of scope)
– Modify functionality
– Alter access and rights
![Page 10: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/10.jpg)
Post Compile Injection (out of scope)
• Apktool
• http://code.google.com/p/android-apktool/
• Is a tool for reverse engineering 3rd party, closed, binary Android apps. It can decode resources to nearly original form and rebuild them after making some modifications; it makes possible to debug smali code step by step.
• Smali – assember and disassembler tools for Android’s dex format
![Page 11: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/11.jpg)
Dex 2 Jar
• Convert dex format to jar
• Written by Chinese student
• http://code.google.com/p/dex2jar/
• We use it for source disasemple
![Page 12: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/12.jpg)
Dex2Jar
![Page 13: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/13.jpg)
JD Decompiler
• Cool from previous step we have jar file
• JD decomplier is tool to convert jar/class
files to java sources !
• http://java.decompiler.free.fr/
![Page 14: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/14.jpg)
JD Decompiler
![Page 15: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/15.jpg)
Obfuscation
• Obfuscation is the deliberate act of
creating obfuscated code, i.e. source or
machine code that is difficult for humans to
understand.
• Programs known as obfuscators transform
readable code into obfuscated code using
various techniques.
![Page 16: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/16.jpg)
Why
• Mainly to defend against Software Reverse
Engineering
• We can only make it more difficult for reverse
engineers
• Available obfuscating tools work in the same
way as compiler optimizers
• Reduce required space and time for compilation
![Page 17: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/17.jpg)
Layout Obfuscation
• Changing variables
• Removing comments
• Both methods:
– Free of cost
– One way functions
![Page 18: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/18.jpg)
Data Obfuscation
• Encoding
for(int i = 0; i < 100; i++ ){}
f(i) = 2*i+5
for(int i = 5; i < 205; i =i+2){}
• Split array
• Change ordering
– Variable declaration spread out
![Page 19: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/19.jpg)
• Hide information flow – Dead code – note that
compiler removes dead code, however obfuscators run after compilation complete on class files.
– Parallelize Code
Control Obfuscation
![Page 20: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/20.jpg)
Proguard
• Android comes with obfuscation proguard
tool, which is good
• However never ship out the APK before
disassembling it by yourself
![Page 21: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/21.jpg)
Check Commercial Tools
• DashO
http://www.preemptive.com/products/dash
o
• I worked with, strongly recommended
![Page 22: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/22.jpg)
Use NDK
• For exceptional situations (which are rare !) consider using NDK and write your algorithms in native code
• For example you have a really fast number crunching, such as matrix inverse algorithm; and you don't want it to be known, you can write in C and ship
• ARM disassembly is not good
• NDK usually used for legacy code, such as cross platform mobile library for OMA DM protocol written in C
• NDK is in Appendix 1, for interested
![Page 23: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/23.jpg)
References
• Consider the following
http://siis.cse.psu.edu/dare/index.html
![Page 24: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/24.jpg)
Android is getting better
• Application verification — Users can choose to enable
“Verify Apps" and have applications screened by an
application verifier, prior to installation. App verification can
alert the user if they try to install an app that might be harmful;
if an application is especially bad, it can block installation.
• From Jelly Bean the application will be downloaded encrypted
via AES symmetric key between Play and Device
• http://nelenkov.blogspot.co.il/2012/07/using-app-encryption-in-
jelly-bean.html
• Way to break build custom ROM.
![Page 25: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/25.jpg)
![Page 26: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/26.jpg)
Plan
• Application Integration Layer
– MVVM
– Key Classes
– Communication Mechanisms
• Analysis
“Android SDK and API are for writing user
applications and not core libraries”
![Page 27: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/27.jpg)
![Page 28: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/28.jpg)
Android application usually consists
of:
• Java classes that are subclasses of main Android SDK classes: – Views
– Activities/Fragments
– Content Providers
– Services
– Intents
• Manifest
• Resources like strings, images etc
• Files
![Page 29: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/29.jpg)
MVVM
• Android application architecture follows very modern
Model-View-ViewModel(MVVM) architectural pattern in
how it handles relationships between GUI and a logic
supporting the GUI.
• What are corresponding Android components ?
![Page 30: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/30.jpg)
MVVM
• MVVM architecture was created in attempt to solve a disparity of skills which occurs when e.g. a Java developer tries to build GUI in Swing or a Visual C++ developer tries to build GUI in MFC.
• Developers are smart folks and have many skills, but building GUIs requires quite different talents than those the developers usually have.
• It is work more suitable for GUI designers. Good GUI designers are more artists and a user experience professionals than experts in designing and writing code
• Clearly, it would be better if a GUI designer was designing a GUI and a developer was writing a code which implements a logic behind the GUI, but such technologies as Swing or MFC simply do not allow this.
![Page 31: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/31.jpg)
MVVM – separate responsibility
• GUI development is done by a GUI designer in technology more or less natural for this task (XML)
• Logic behind the GUI is implemented by a developer as ViewModel (which actually means Model of View) component
• Functional relationships between GUI and ViewModel are implemented through bindings that essentially define rules like “if a button A is clicked, method onButtonAClick() should be called on ViewModel”. Bindings can be written in the code or defined in a declarative way in XML.
![Page 32: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/32.jpg)
MVVM
• MVVM architecture is used in one way or
another by all modern GUI technologies
like Microsoft WPF (XAML)
and Silverlight, HTML5
![Page 33: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/33.jpg)
Context
• Android Context class – mighty player behind the scene
• The class is rarely mentioned in various manuals and articles; at the same time it is arguably the most important class in the whole set of Android SDK.
![Page 34: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/34.jpg)
Context
• It is ancestor (although not a direct parent) of such
classes Activity, Application, Service classes
• Context also implements the biggest portion of
functionality of those classes.
• To summarize Context class provides access to various
infrastructure functionalities provided by Android
• Do you think Context is a good name ?
![Page 35: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/35.jpg)
Context Getting Access to Managers
• AssetManager
• AccessebilityManager
• AccountManager
• ActivityManager
• AlarmManager
• AudioManager
• …
![Page 36: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/36.jpg)
Access to
• API for working with database files (not DB
functionality!)
• API for working with files and directories
• API for working with permissions
• API for binding to services and
starting/stopping them
• …
![Page 37: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/37.jpg)
Activity
• Is class and its subclasses are the ones that provide logic behind the GUI. Actually it corresponds to ViewModel in architecture pattern (MVVM). Relationship between subclasses of Activity and GUI layout is 1-to-1; normally each subclass of Activity has one GUI layout associated with it and vice-versa. Activity has a lifecycle.
• During the lifecycle Activity can be in one of three states: – Active and running when its GUI is in the foreground (technically
speaking – on top of activity stack)
– Paused if its GUI lost focus but it is still visible. No code is executed in this state
– Stopped if its GUI is not visible. No code is executed in this state
![Page 38: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/38.jpg)
Activity Life Cycle
User implemented
callbacks (template
methods) that are called
upon the relevant events
In case you override
callback please pay
attention to all edges
(onResume preceded
onPause)
![Page 39: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/39.jpg)
Activity
• Here is an example. Let’s assume our application has GUI screen A and GUI screen B. A user accesses screen A first and then screen B; at this point screen A is not visible anymore.
• This means screen A and all logic that supports it may or may not be kept in memory.
![Page 40: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/40.jpg)
No Sharing Between Activities
• Since there is no guarantee that objects associated with screen A exist in memory while screen B is shown, the developer writing screen B logic must not expect that a certain object instantiated for screen A is still in memory.
• A side result of this is that Android architecture enforces shared nothing architectural style for Android applications.
• This means that different parts of Android application can invoke each other and communicate between them only in an explicit way; there is no shared state between them in-memory, except application object
![Page 41: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/41.jpg)
Java Memory Model
• In a “regular” Java an object is kept in
memory until it is garbage collected. The
garbage collection occurs only if an object
does not have any reference to it from
other “live” objects
![Page 42: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/42.jpg)
Android Memory Model
• If a certain GUI gets hidden (it is not visible on the screen),
there is no guarantee that it will be kept in memory even if the
application intends to use it later.
• It might be kept in memory alright if Android OS has enough
free memory, but it can be garbage collected as well at any
moment when the OS finds that it needs more free memory.
• If an application process does not show any GUI to the user
at the moment, it can be legitimately terminated by Android
OS (there is one exception to this rule related to Android
Services).
![Page 43: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/43.jpg)
Activity
• Activity code runs only when the Activity GUI is visible
and has focus. Also there is no guarantee
that Activity object and its associated objects are in
memory while the Activity is paused or stopped
• Design carefully code in activity. One of key anti patterns
is code in activity that has to be in service
• Design your activities thin
![Page 44: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/44.jpg)
Fragments
• Honeycomb introduced Fragments to support reusing portions of UI
and logic across multiple activities in an app
• The larger screen sizes found on most tablets added an extra layer
of complexity to Android development—a layout designed for the
small screen does not necessarily work as well for larger screens,
and vice-versa
• Fragments can be thought of as user interface modules. They let the
developer divide up the user interface into isolated, reusable parts
that can be run in separate Activities. At run time, the Activities
themselves will decide which Fragments to use
![Page 45: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/45.jpg)
Example
![Page 46: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/46.jpg)
Activity Fragments
• Activity uses APIs of FragmentManager to load relevant fragments (add, remove, replace …)
• Activity serves as an intermediary between fragments. – Fragments don’t have intent filters; an Intent can’t directly
trigger a fragment.
– Let the activity respond to intents and fragment callbacks.
– The activity will know if it can “route” a event to a fragment it contains, or if it needs to start another activity to handle the event
• For backward compatibility on pre-Honeycomb devices use v4 support library
• Problem – increases application size and processing
![Page 47: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/47.jpg)
View
• View class is a base class for all GUI widgets. Android application GUI is a tree of instances of its subclasses i.e. GUI widgets.
• One can build the tree programmatically, but this is not how you should do this. A lot of companies provide “same layout” for iPhone/Android based on programmatically based UIs this is always wrong
• GUI is defined by an XML GUI definition (layout file) and inflated automatically into a tree of corresponding objects at runtime.
• View follows Composite pattern
![Page 48: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/48.jpg)
Content Provider
• Is a class and its subclasses correspond to Model in MVVM architecture. In most practical cases it is a wrapper around SQLite database with rather fancy URI-based way to query the database.
• Given that query()method of ContentProvider returns Cursor object which is quite similar to JDBC ResultSet interface and the way how the query is made,
• Seems real purpose of ContentProviders is to encapsulate a database.
![Page 49: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/49.jpg)
Service
• How do you define it ?
• Why it is there is first place ?
![Page 50: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/50.jpg)
Why Service ?
• Activity is active and running only when its GUI is on foreground. As soon as another Activity GUI comes in front of the current one, the current one stops running even if it was doing something.
• What if you need to perform certain operation even when the process which tries to perform it is not on foreground? You can’t do this with Activity.
• Can’t do this with ContentProvider as well since it does not have its own lifecycle and it can run only while Activity which uses it is active.
![Page 51: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/51.jpg)
Service
• Here Service comes to the rescue. It can be executed even when the process it runs within is not on a foreground.
• So if you develop Activity which must perform a long running operation which should be completed even while running in background, you should create Service implementing that operation and invoke it from Activity.
![Page 52: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/52.jpg)
Manifest(all global data)
• It names the Java package for the application. The package name serves as a unique identifier for the application.
• It describes the components of the application — the activities, services, broadcast receivers, and content providers that the application is composed of. It names the classes that implement each of the components and publishes their capabilities (for example, which Intent messages they can handle). These declarations let the Android system know what the components are and under what conditions they can be launched.
• It determines which processes will host application components.
• It declares which permissions the application must have in order to access protected parts of the API and interact with other applications.
• …
![Page 53: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/53.jpg)
Resources
• Pictures
• GUI layouts (XML files)
• Menu definitions (XML files)
• Textual strings
• R.java – programmatic/type safe access to all resources
• Hack – applying reflection to R class thus can do
programmatic manipulation of layouts in run time.
![Page 54: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/54.jpg)
Communication Patterns
• Message Passing
• Publisher Subscriber
• Content Provider
• Service
– Local
– Remote
![Page 55: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/55.jpg)
Message Passing
public void do() {
Intent explicitIntent = new
Intent(this,InvokedActivity.class);
explicitIntent.putExtra(“Key”,
“Value”);
startActivity(explicitIntent);
}
Connect between
components
Pass values
Start !
![Page 56: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/56.jpg)
Message Passing
• Simplest communication mechanism. It is used to start
an Activity or a Service. It is implemented via three
methods on Context and one method on Activity class:
– startActivity
– startActivityForResult
– startService
• In both cases Intent class plays a role of a message
passed (and only zero or one component gets it)
![Page 57: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/57.jpg)
Message Passing
• How does Android know which Activity or Service should receive the message?
• Intent may specify a name of the target component explicitly. Such Intents are called “explicitIntents” and they specify a target component via setComponent or setClass methods of Intent class.
• Implicit Intents – only the action (based on intent resolution) – late binding
![Page 58: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/58.jpg)
Publisher Subscriber
GMail
Contacts
Home
Blogger
Chat
Client component makes a request for a specific
action
“Pick photo”
Picasa
System picks best component for that action
New components can use existing functionality
Blogger
Photo Gallery
![Page 59: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/59.jpg)
Publisher Subscriber
• Publish/subscribe communication mechanism involves the
same Intent class as a message and the same intent filters as a
resolution mechanism defining target components, but it works quite
differently.
• Intents used for publish/subscribe communication are called
“broadcast Intents”. Those broadcast Intents can be delivered to
BroadcastReceivers only. SinceBroadcastReceiver is a class
and Activity and Service are classes as well, neither Activity not
Service can receive the broadcast Intent (Java prohibits multiple
inheritance).
• Also, unlike Intent used for message passing, a single broadcast
Intent can be delivered to many target components.
![Page 60: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/60.jpg)
2 Mechanisms
• Normal broadcast which is implemented
by sendBroadcast() and
sendStickyBroadcast() methods of Contex
t class
• Ordered broadcast which is implemented
by sendOrderedBroadcast() and
sendOrderedStickyBroadcast()
![Page 61: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/61.jpg)
Publisher Subscriber
• Normal broadcast mechanism delivers
the Intent to all eligible BrodcastReceivers
asynchronously and they act on it independently
• One BrodcastReceiver can’t affect either how
another BrodcastReceiver is reacting on
the Intent or whether the Intent is delivered to
another BroadcastReceiver. It is a regular
pub/sub pattern.
![Page 62: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/62.jpg)
Ordered Broadcast Receivers
• Ordered broadcast mechanism delivers the Intent to eligible BrodcastReceives in a sequential manner, i.e.toone at a time. Due to this each BrodcastReceiver can potentially:
• Use results produced by previous BroadcastReceivers that worked on the sameIntent
• If needed, abort further processing of the Intent
• By executing ordered broadcast, a component which initiated it gets opportunity to receive the result of processing the Intent by all BroadcastReceivers in the chain.
• Ordered broadcast actually is an implementation of chain of responsibility pattern.
• Haven’t used them yet Your experience ?
![Page 63: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/63.jpg)
Sticky
• Sticky broadcasts are versions of the corresponding regular broadcasts.
• The difference is the Intent is available until it is explicitly removed by removeStickyBroadcast method of Contextclass. Please note, this type of broadcast should be used with great caution since not removing the sticky Intents will result in a memory leak.
• One example of a sticky broadcast sent via the operating system is ACTION_BATTERY_CHANGED. When you call registerReceiver() for that action -- even with a null BroadcastReceiver -- you get the Intent that was last broadcast for that action.
![Page 64: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/64.jpg)
Late binding of ContentProvider
• ContentProvider class is essentially a wrapper
around SQLite database
• There are many ways how Android code can
use ContentProviders.
– Proxy - ContentProviderClient, which implements
proxy design pattern
– Cursor - Some of them return an instance of
Cursor class which allows iterating through data set
returned byContentProvider.
![Page 65: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/65.jpg)
Late binding and Inter-process Procedure
Communication (IPC) of Service
• Apart of ContentProvider class there is Service class which architecturally
plays the same role of Model in MVVM architecture pattern.
• There are two types of Service and each requires a separate
communication mechanism:
– Local Service which runs within the same process where it is invoked.
– Remote Service which runs within another process from where it is
invoked.
• It is worth mentioning that the same Service may be used as both Local and
Remote; the difference is in where the component which invokes
the Service is located (within the same process or in another process).
![Page 66: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/66.jpg)
Local Service
• Services which can be bound only from the same process.
• Implement the service's interface extending the android.os.Binder
class
• Return an instance of the implemented interface from the service's
onBind()callback
• The client(Activity) will use the achieved object to execute methods
remotely on the bound service
• The implementation could allow even calls on Service's methods!
![Page 67: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/67.jpg)
Remote Service
• Such type of service is accessed through a sort of IPC call implemented
using either Messenger or AIDL (Android Interface Definition Language)
• If you need to implement a bound Service which have to be reached from
outside your application but don't want to deal with AIDL use the
android.os.Messenger class!
• This class implements a message passing channel handling transparently
the IPC mechanism
• Messengers are associated to a custom Handler implementation which will
handle the incoming messages.
![Page 68: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/68.jpg)
Your Classes
• Of course, Android application developer
is not limited to just extending Android
SDK classes. She can write her own
classes as she wants. But all they will be
just “helper classes” of sorts for those
main classes derived from Android SDK
classes.
• Make sure you add them in right place
![Page 69: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/69.jpg)
![Page 70: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/70.jpg)
UI Structure
Widget Unique Detail
Search
Common
Action 1
Common
Action 2
Action Bar App Home
Search
Common
Action 1
Common
Action 2
Activities
App
Dashboard
Activities
![Page 71: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/71.jpg)
Google’s Recommendation
• Your application most of the time sleeping,
but has to respond fast
![Page 72: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/72.jpg)
Architectural Analysis
• Great Architectural Decisions
– Linux kernel – free, stable, robust
– VM based applications – cross device
platform (ARM, x86 …)
– MVVM –most modern UI model
![Page 73: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/73.jpg)
Architectural Analysis
• Questionable Implementation Issues
– Why both Service and Activity inherit from Context, violation of
Solid principle. Better to pass context as parameter similar to
servlets API
– Service and Content have a lot of common functionality both are
model in MVVM, why need both ? Or at least provider a common
ancestor
– Intent plays too many roles … why not to have separated
classes
– MVVM connection mechanisms – last thing to say they are easy
![Page 74: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/74.jpg)
References
• http://vladnevzorov.com/ deep analysis
took many ideas (with permission)
• Android Developer’s site
• Various blogs
• Stackoverflow
• Android sources
![Page 75: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/75.jpg)
![Page 76: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/76.jpg)
Code Bloat in Application
• Code bloat is bad
• Usually the code bloat is in with our business
logic, because the other parts are Android
framework components that we extend
• In this part we explore relevant design patterns
to cope with code bloat in our applications
![Page 77: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/77.jpg)
Gang Of Four
![Page 78: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/78.jpg)
Gang of 4 Intro
• The book's authors are Erich Gamma, Richard
Helm, Ralph Johnson and John Vlissides with a foreword
by Grady Booch. They are often referred to as the Gang
of Four, or GoF
• The book is divided into two parts, with the first two
chapters exploring the capabilities and pitfalls of object-
oriented programming, and the remaining chapters
describing 23 classic software design patterns
![Page 79: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/79.jpg)
GoF Pattern Structure
• Pattern Name and Classification: A descriptive and unique name that helps in identifying and referring to the pattern.
• Intent: A description of the goal behind the pattern and the reason for using it.
• Also Known As: Other names for the pattern.
• Motivation (Forces): A scenario consisting of a problem and a context in which this pattern can be used.
• Applicability: Situations in which this pattern is usable; the context for the pattern.
• Structure: A graphical representation of the pattern. Class diagrams and Interaction diagrams may be used for this purpose.
• Participants: A listing of the classes and objects used in the pattern and their roles in the design.
• Collaboration: A description of how classes and objects used in the pattern interact with each other.
• Consequences: A description of the results, side effects, and trade offs caused by using the pattern.
• Implementation: A description of an implementation of the pattern; the solution part of the pattern.
• Sample Code: An illustration of how the pattern can be used in a programming language
• Known Uses: Examples of real usages of the pattern.
• Related Patterns: Other patterns that have some relationship with the pattern; discussion of the differences between the pattern and similar patterns.
![Page 80: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/80.jpg)
Cont
• Structural
– Composite
– Decorator
– Adapter
– Flyweight
– Bridge
• Behavioral
– Observer
– Command
– State
![Page 81: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/81.jpg)
Cont
• Behavioral
– Iterator
– Interpreter
– Mediator
– Memento
– Visitor
– Template Method
– Strategy Chain of Responsibility
![Page 82: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/82.jpg)
Pattern Definition
82
• A particular recurring design problem that arises in
specific design contexts, and presents a well-proven
generic scheme for its solution.
• The solution scheme is specified by describing its
constituent components, their responsibilities and
relationships, and the ways in which they collaborate
• Context(Problem) + Structure(UML and implementation)
![Page 83: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/83.jpg)
A pattern must:
• Solve a problem- it must be useful!
• Have a context - it must describe where the
solution can be used
• Recur - it must be relevant in other situations
• Teach - It must provide sufficient understanding
to tailor the solution
• Have a name - it must be referred to consistently
![Page 84: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/84.jpg)
Design Patters – Format & Structure
• Christopher Alexander and "A Timeless Way of Building“
• A pattern is a careful description of a perennial solution to a
recurring problem within a building context, describing one of the
configurations which brings life to a building.
• Each pattern describes a problem which occurs over and over again
in our environment, and then describes the core solution to that
problem, in such a way that you can use the solution a million times
over, without ever doing it the same way twice."
• A pattern language is a network of patterns that call upon one
another. Patterns help us remember insights and knowledge about
design and can be used in combination to create solutions.
![Page 85: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/85.jpg)
Design Patterns are not !
• Patterns fetish
– Try to incorporate as much patterns as
possible
• Wrong/incomplete understanding of the
context
![Page 86: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/86.jpg)
Design Patterns are not !
• Abuse “My module incorporates 17 of 23 GoF
patterns !”
Don’t confuse design patterns with always-
do rules
• Don’t to start using design patterns. All of
them. At once. Think ! Evaluate !
![Page 87: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/87.jpg)
Benefits
• Design patterns enable large-scale reuse of software architectures. They also help document systems to enhance understanding
• Patterns explicitly capture expert knowledge and design tradeoffs, and make this expertise more widely available
• Patterns help improve developer communication. Pattern names form a vocabulary
• Patterns help ease the transition to object-oriented technology (refactoring …)
![Page 88: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/88.jpg)
Bloat Code
If(metaDataElement.getState() == State.Update &&
metaDataElement.getState != State.Requested )
{
doA()
return;
} else
If(metaDataElement.getState() == State.Process ||
metaDataElement.getState != State.META )
…
![Page 89: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/89.jpg)
State
![Page 90: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/90.jpg)
State Functional Requirement
• An object’s behavior is a function of its
state, and it must change its behavior at
run-time depending on that state.
• An application is characterized by large
and numerous case statements that
control the application behavior (Why is it
bad ?)
![Page 91: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/91.jpg)
State
![Page 92: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/92.jpg)
Solution
• Identify an existing class, or create a new class, that will serve as the “state machine” from the client’s perspective. That class is the “wrapper” class.
• Create a State base class that replicates the methods of the state machine interface. Each method takes one additional parameter: an instance of the wrapper class. The State base class specifies any useful “default” behavior.
• Create a State derived class for each domain state. These derived classes only override the methods they need to override.
• The wrapper class maintains a “current” State object.
• All client requests to the wrapper class are simply delegated to the current State object, and the wrapper object’s this pointer is passed.
• The State methods change the “current” state in the wrapper object as appropriate.
![Page 93: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/93.jpg)
Analysis
• State objects are often Singletons.
• Flyweight explains when and how State objects can
be shared.
• The implementation of the State pattern builds on
the Strategy pattern. The difference between State
and Strategy is in the intent. With Strategy, the
choice of algorithm is fairly stable. With State, a
change in the state of the “context” object causes it
to select from its “palette” of Strategy objects.
![Page 94: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/94.jpg)
Solution
• Class MetaDataElement holds State current object
• Classes (from State interface)
– StateApproved
– StateSynced
– ….
• Each State object holds the relevant transitions related
to it
• Easy to add new states
![Page 95: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/95.jpg)
Code Bloat
• A lot of code that is not clear what is doing
and why is needed
• Classes like actions/commands etc’
• Parsing logic in all places
• Switch cases and ifs
![Page 96: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/96.jpg)
Interpreter
![Page 97: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/97.jpg)
Interpreter Functional Requirement
• A class of problems occurs repeatedly in a
well-defined and well-understood domain.
If the domain were characterized with a
“language”, then problems could be easily
solved with an interpretation “engine”.
![Page 98: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/98.jpg)
Interpreter
![Page 99: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/99.jpg)
Problem
• Given a language, define a representation
for its grammar along with an interpreter
that uses the representation to interpret
sentences in the language.
• Map a domain to a language, the
language to a grammar, and the grammar
to a hierarchical object-oriented design.
![Page 100: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/100.jpg)
Solution
• Decide if a “little language” offers a justifiable return on investment.
• Define a grammar for the language.
• Map each production in the grammar to a class.
• Organize the suite of classes into the structure of the
Composite pattern.
• Define an interpret(Context) method in the Composite hierarchy.
• The Context object encapsulates the current state of the input and
output as the former is parsed and the latter is accumulated. It is
manipulated by each grammar class as the “interpreting” process
transforms the input into the output.
![Page 101: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/101.jpg)
Analysis
• Considered in its most general form (i.e. an operation distributed over a
class hierarchy based on the Composite pattern), nearly every use of
the Composite pattern will also contain the Interpreter pattern. But the
Interpreter pattern should be reserved for those cases in which you
want to think of this class hierarchy as defining a language.
• Interpreter can use State to define parsing contexts.
• The abstract syntax tree of Interpreter is a Composite (therefore Iterator
and Visitor are also applicable).
• Terminal symbols within Interpreter’s abstract syntax tree can be shared
with Flyweight.
• The pattern doesn’t address parsing. When the grammar is very
complex, other techniques (such as a parser) are more appropriate.
![Page 102: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/102.jpg)
Solution
• Take ideas from other languages to
implement mini interpreter
![Page 103: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/103.jpg)
Code Bloat
• If(isCollision)
if(Collision == Take their)
Action.doTakeThier
else (Collision == TakeLocal)
Action.doTakeLocal
…
What is more actions needed and more collision types be
available (such as merge or notify them)
![Page 104: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/104.jpg)
Strategy
![Page 105: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/105.jpg)
Strategy Functional Requirements
• We want to define a family of algorithms
and make them interchangeable.
• We want let the algorithms vary
independently from clients that use them
![Page 106: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/106.jpg)
Route to Airport via various means
![Page 107: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/107.jpg)
Strategy
![Page 108: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/108.jpg)
Solution
• Identify an algorithm (i.e. a behavior) that the client
would prefer to access through a “flex point”.
• Specify the signature for that algorithm in an interface.
• Bury the alternative implementation details in
derived classes.
• Clients of the algorithm couple themselves to
the interface.
![Page 109: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/109.jpg)
Analysis
• Strategy is like Template Method except in its granularity.
• State is like Strategy except in its Problem.
• Strategy lets you change the guts of an object. Decorator
lets you change the skin.
• State, Strategy, Bridge (and to some degree Adapter)
have similar solution structures. They all share elements
of the ‘handle/body’ idiom. They differ in Problem - that
is, they solve different problems.
• Strategy objects often make good Flyweights.
![Page 110: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/110.jpg)
Solution
CollisionAction
HandleCollision(CollisionStrategy s, File f)
{
return s.appplyStaregy(f)
}
![Page 111: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/111.jpg)
![Page 112: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/112.jpg)
• In this part we are going to explore the
Effective/right usage of the Java i.e. linqa
franca of Android
• Cover the important topics relevant for
Android
• Mastering effective language usage will
leverage you code and applications in
terms of:
– Reusability
– Security
– Maintainability
![Page 113: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/113.jpg)
Based on Effective Java Book
![Page 114: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/114.jpg)
![Page 115: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/115.jpg)
Utility Classes
• Class that is just grouping of static
methods and static fields.
• Bad reputation – abuse them while
thinking in terms of objects
• java.lang.Math , java.util.Arrays
![Page 116: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/116.jpg)
Utility classes
• These classes are not designed to be
instantiated (nonsense for such objects)
• However without constructor , the complier
provides synthesized empty default
constructor.
• To a user this constructor is un-
distinguishable
![Page 117: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/117.jpg)
Wrong Solution
• Make class abstract doesn’t work (the
class can be subclassed and the subclass
can be instantiated)
• Misleads the user class is designed for
inheritance.
![Page 118: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/118.jpg)
Solution
public class UtilityClass{
private UtilityClass(){
throws new AssertionError();
}
}
![Page 119: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/119.jpg)
Discussion
• Constructor is private thus invisible outside
class
• AssertionError provides insurance in case
the constructor is accidentally invoked
inside class
• No subclasses
![Page 120: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/120.jpg)
![Page 121: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/121.jpg)
Classes and Interfaces
• When class implements an interface, the
interface serves as type that can be used
to refer to instances of the class
• It is inappropriate to define interface for
any other use
![Page 122: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/122.jpg)
Bad Example
public interface Constants{
static final int NUM1=0;
static final int NUM2=0;
static final int NUM3=0;
}
![Page 123: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/123.jpg)
Discussion
• Class uses constants internally is an
implementation data
• Confuses users
• Worse interface is a commitment, in future
class modified no use of constants , the
class still polluted with constants
![Page 124: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/124.jpg)
Better version
public class MyConstants{
// prevent instantiation
private MyConstants(){}
static final int NUM1=0;
static final int NUM2=0;
static final int NUM3=0;
}
![Page 125: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/125.jpg)
![Page 126: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/126.jpg)
Intro
• A nested class is a class defined within
another class to serve it:
– Static member class
– Non static member class
– Anonymous class
– Local class
• The last three are inner classes
![Page 127: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/127.jpg)
Static member classes
• Public helper class used with conjunction
with its outer class
• Access to all static outer class private
members
• Associated with class and not object name
![Page 128: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/128.jpg)
Static member class
class Filter{
static class Criterion{
}
}
filter.addCriterion(new
Filter.Criterion());
![Page 129: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/129.jpg)
Non-static member class
• Each instance associated with enclosing
instance of its containing class
• Association takes time and place
• Common usage Adaptor pattern
![Page 130: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/130.jpg)
Non static member class (adaptor
example)
public class MySet<E> extends AbstractSet<E>{
public Iterator<E>iterator(){
return new MyIterator();
}
private class MyIterator implements Iterator<E>{
}
}
![Page 131: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/131.jpg)
Rule
• If you declare a member class that doesn’t
require access to an enclosing instance ,
always put static modifier in its declaration
![Page 132: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/132.jpg)
Anonymous class
• Declared and instantiated with in the same
statement
• No name and instantiated only one
![Page 133: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/133.jpg)
Anonymous class
String[] filelist = f.list(new
FilenameFilter() {
public boolean
accept(File f, String s) {
return s.endsWith(".java");
}
}); // Don't forget the parenthesis and
//semicolon that end the method call! …
![Page 134: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/134.jpg)
Local class
• A local class is declared locally within a
block of Java code, rather than as a
member of a class
• Typically, a local class is defined within a
method, but it can also be defined within a
static initializer or instance initializer of a
class.
![Page 135: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/135.jpg)
Local class
// This method creates and returns an Enumeration //object
public java.util.Enumeration enumerate(){
// Here's the definition of Enumerator // as a local class
class Enumerator implements java.util.Enumeration { }
// Now return an instance of the //Enumerator class defined directly //above
return new Enumerator();
}
![Page 136: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/136.jpg)
![Page 137: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/137.jpg)
Intro
• Enums were added at Java 1.5
• Enumerated type -is a type whose values
consist of a fixed set of constants
• In Java Enum is a class (as opposed to
C++)
![Page 138: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/138.jpg)
Don’t Do it(int Enum pattern)
final int Apple1=1;
final int Apple2=2;
final int Apple3=3;
final int
Orange1=1;
final int
Orange2=3;
• No type safety (mix apples with oranges)
• No convenience
![Page 139: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/139.jpg)
Fix
public enum Apple
{APP1,APP2};
public enum Orange
{ORANGE1,ORANGE2}
;
![Page 140: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/140.jpg)
Basic Idea
• Enums are classes that export one
instance for each enumeration constant
via a public static final field
• Instance controlled
• Generalizations of singletones
![Page 141: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/141.jpg)
Static member classes
• Public helper class used with conjunction
with its outer class
• Access to all static outer class private
members
• Associated with class and not object name
![Page 142: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/142.jpg)
Static member class (look at list)
public enum Planet { MERCURY(3.302e+23, 2.439e6), private final double surfaceGravity; // In m / s^2 private static final double G = 6.67300E-11; // Constructor Planet(double mass, double radius) { surfaceGravity = G * mass / (radius * radius); } public double surfaceWeight(double mass) { return mass * surfaceGravity; // F = ma } }
![Page 143: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/143.jpg)
Notes from example
• Constructor inside enum
• Enums are immutable , thus all fields final
• Static values() array
![Page 144: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/144.jpg)
Design
• Enum should be top level class
• Consistency across the API
![Page 145: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/145.jpg)
![Page 146: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/146.jpg)
Don’t do it/Ill design
try{
int i=0;
while(true)
range[i++].
operate;
}catch(ArrayOutOfBo
unds…){
}
• May be save array checking overhead - WRONG
• Exception no fast design incentive
• Try/catch – optimization limit
• JVM optimizes array check
![Page 147: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/147.jpg)
Rule
• Use exceptions only for exceptional
conditions
• Never use exceptions for ordinary control
flow
• A well designed API must not force its
clients to use exceptions for ordinary
control flow
![Page 148: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/148.jpg)
Checked Exceptions
• Try/catch block
• Use only for conditions from which the
caller can reasonably expect to recover
• invalid user input, database problems,
network outages, absent files
• Provide API to check the state
![Page 149: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/149.jpg)
Runtime Exceptions
• Programming errors, pre-conditions
violations
• ArrayIndexOutOfBounds
,IllegalArguments, NullPointer,IllegalState
![Page 150: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/150.jpg)
Favor The Use Of Standard
Exceptions
• API easier to learn
• Standard reuse
• Smaller memory footprint
![Page 151: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/151.jpg)
Most Commonly Reused
• IllegalArgumentException
• IllegalStateException
• NullPointerException
• IndexOutOfBoundsException
• ConcurrentModificationException
• UnsupportedOperationException
![Page 152: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/152.jpg)
Throw Exceptions Appropriate To the
Abstraction
• Higher layers should catch lower level
exceptions and, in their place , throw
exceptions that can be explained in terms
of higher level abstractions
152
![Page 153: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/153.jpg)
Code Example Translation
try{
}catch(LowLevelException e){
throw new
HighLevelException(…);
}
![Page 154: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/154.jpg)
Code Example Chaining
try{
}catch(LowLevelException cause){
throw new
HighLevelException(cause);
}
![Page 155: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/155.jpg)
Exception Chaining
• Don’t overuse it
• Best way is to avoid low level exceptions
by parameters checking
![Page 156: Advanced android](https://reader033.vdocuments.site/reader033/viewer/2022052905/5585561fd8b42a78328b4844/html5/thumbnails/156.jpg)