Separating Domain Model and Application Model

Warning: Illegal string offset 'language' in /var/www/vhosts/ansuz.nl/subdomains/blog/httpdocs/wp-content/plugins/igsyntax-hiliter/classes/frontend.php on line 510 Warning: ksort() expects parameter 1 to be array, string given in /var/www/vhosts/ansuz.nl/subdomains/blog/httpdocs/wp-content/plugins/igsyntax-hiliter/classes/frontend.php on line 513

Let’s take a simple retail app as an example. The app has the following (partial) domain model:

It can be quite tempting to use a domain model as an application model (as in the “M” in MVC). Your application obviously needs to use the data presented in the domain model. At first, it may seem logical to access this data directly, e.g. for showing a product name on a product details page. There are several problems with this approach though.

The domain model may be too verbose for your application’s needs. Let’s say you don’t care about the image details, but only want the URL. The app may also want to check to see if a product has an image associated with it before trying to display it. To solve this, the Product and Image objects above can be combined into one, like below.

Another benefit is that you keep things DRY. The validation logic is not repeated in various classes (think different Presenters in the MVP pattern).

To facilitate the conversion from domain model to app model, you could introduce a converter class. Something like the below.

  1. public class ModelConverter {
  2.     public AppProduct convertProduct(DomainProduct product) {
  3.         // Imagine a nice implementation here...
  4.         return appProduct;
  5.     }
  6. }

During conversion you can also do some more data validation to make sure your app doesn’t break when back-end data is incomplete. In this example, for instance, you shouldn’t rely on the image always being populated in the Product object.

All in all, separating your domain model from your application model will help you build a more stable app, trim data floating around and reduce code duplication (by centralising data validation).

DroidCon UK 2015 day 1

Warning: Illegal string offset 'language' in /var/www/vhosts/ansuz.nl/subdomains/blog/httpdocs/wp-content/plugins/igsyntax-hiliter/classes/frontend.php on line 510 Warning: ksort() expects parameter 1 to be array, string given in /var/www/vhosts/ansuz.nl/subdomains/blog/httpdocs/wp-content/plugins/igsyntax-hiliter/classes/frontend.php on line 513 Warning: Illegal string offset 'language' in /var/www/vhosts/ansuz.nl/subdomains/blog/httpdocs/wp-content/plugins/igsyntax-hiliter/classes/frontend.php on line 510 Warning: ksort() expects parameter 1 to be array, string given in /var/www/vhosts/ansuz.nl/subdomains/blog/httpdocs/wp-content/plugins/igsyntax-hiliter/classes/frontend.php on line 513 Warning: Illegal string offset 'language' in /var/www/vhosts/ansuz.nl/subdomains/blog/httpdocs/wp-content/plugins/igsyntax-hiliter/classes/frontend.php on line 510 Warning: ksort() expects parameter 1 to be array, string given in /var/www/vhosts/ansuz.nl/subdomains/blog/httpdocs/wp-content/plugins/igsyntax-hiliter/classes/frontend.php on line 513

9.00 Keynote: The long road
Speaker: Sandro Mancuso

Inspirational talk about how to find the job that will be the next step in your career.
Your personal career goals can be very different from a career within a company.

10.30 RxJava – Get Reactive
Speakers: Pascal Welsch and Wolfram Rittmeyer

RxJava
Beware of backpressure (items emitted too fast) discussed on Wiki as well. Possible solutions:

  • Throttle
  • Buffer
  • Request(n) upstream items

Testing: Use TestSubscriber.

RxAndroid
RxJava bindings for Android.

RxBinding
RxJava binding APIs for Android’s UI widgets.

Type and make network request handling, i.e. type and search. Add the following:

  • .throttleLast(100, MS) – Emit the most recent items emitted by an Observable within periodic time intervals.
  • .debounce(200, MS) – Only emit an item from the source Observable after a particular timespan has passed without the Observable emitting any other items.
  • .onBackPressureLatest() – Is there are still too many, take latest input.

RxLifecycle
Lifecycle handling APIs for Android apps using RxJava.

Other recommendations

  • Mosby – A Model-View-Presenter library for modern Android apps.
  • Nucleus – Nucleus is a simple Android library, which utilizes the Model-View-Presenter pattern to properly connect background tasks with visual parts of an application.

11.30 Gradle (performance)
Speaker: Etienne Studer

Gradle is more than just building. It can also be used for releasing, documentation, etc.

  1. gradle build --rerun-tasks

Rerun tasks even if they are up to date.

Performance improvements:

  • Incremental build feature. Define inputs and outputs for custom tasks.
  • Continuous build feature, faster compilation.
  1. gradle test -t

(Relies on inputs and outputs being defined.)

MOOC: Gradle for Android and Java.

12.30 Land’s End: Creating the flagship mobile VR adventure
Speaker: Peter Pashley

Getting started: Install Unity! and the Oculus SDK.

Nausea

  • Frame rate
  • Texture
  • Don’t highlight lack of positional tracking (Don’t put objects close to user so they won’t try to step / look around it.)
  • Acceleration is bad!

Input

  • Gamepad (Reminds user of the world they are not in.)
  • Gear VR
  • “Gaze” (Look points)

Things that didn’t work

  • Moving things on rails or predefined paths. Limits the user’s freedom.
  • Buttons. Too easy, too little player reward.
  • Unconstrained exploration. Take a wrong route, takes a long time to get back.
  • Path hinting. Focus becomes on following the path and not exploring.
  • Levitating huge objects. Obstructs points of reference and makes players motion sick.

Lookpoints

  • Focussing, aim and hold.
  • Motion, knowing where you’re going to stop moving.
  • Placement, not too many near each other.

14.15 ClassyShark Attack
Speaker: Boris Farber

Fast decompiling/debugging for Android APKs.

Ctrl + s – Save Java file.

Supports 5 binary formats

  • Jar
  • Dex
  • APK
  • Manifest
  • Java class

Project site: https://github.com/googlesamples/android-classyshark

15.15 $N tips for building better apps.
Speaker: Wojtek Kalicinski

Stop running your code
Don’t cram too much into Application.onCreate(). ContentProviders and BroadcastReceivers can cause the method to be invoked.
Solutions:

  • Defer work, lazy load.
  • Stop Services.
  • Disable BroadcastReceivers.

Permissions

  • Use ContentProviders to share files and/or get rid of permissions.
  • Use Intents to get rid of even more.
  • Runtime permissions. <uses-permission-sdk23>
  • AccountPicker.newChooseAccountIntent()

Low memory devices
ActivityManager.isLowRamDevice(), available in M, use

  1. android:extractNativeLibs="false"

Native library cannot be compressed and need to be zipaligned (zipalign -p). Write a small bash script to repackage .so when APK is built.

Accessibility
Accessibility is important, you get a bonus for it.

  • Settings > Accessibility -> Talkback
  • Add android:contentDescription tags. Set it to something meaningful. (For decorative elements, set to @null.)
  • onTouchListener, don’t insert click logic, use View.performClick()

Bonus: No extra work when integrating with the accessibility assistent.

16.15 Democamp Community Demos

  • Lumi Social News – Tinder for news.
  • SendTo – Send messages, text, links, etc to your own devices.
  • Myntra – Fashion / Shopping app. Preloading content for fast user experience.
  • Infinity Loop – Game
  • Sharp SVG lib
  • Lunchbreak (Belgium only) – Order lunch online
  • UI testing in your browser – ??
  • Frisbee GDG – All GDG content in one place.

17.15 Keynote: Managing Expectations: A Manager’s Guide for Managing to Manage Unmanageable Teams Manageably
Speaker: Chet Haase

Hilarious talk about management.

Other

  • Lands of Ruin – Lands of Ruin is a tabletop game where tablets replace classic rulebooks, character cards, stat sheets, and pen-and-paper calculations.
  • Land’s End – Mobile VR game.
  • Vysor – Lets you view and control your Android on your computer. Easy peasy.

Using SSL right on Android

Warning: Illegal string offset 'language' in /var/www/vhosts/ansuz.nl/subdomains/blog/httpdocs/wp-content/plugins/igsyntax-hiliter/classes/frontend.php on line 510 Warning: ksort() expects parameter 1 to be array, string given in /var/www/vhosts/ansuz.nl/subdomains/blog/httpdocs/wp-content/plugins/igsyntax-hiliter/classes/frontend.php on line 513 Warning: Illegal string offset 'language' in /var/www/vhosts/ansuz.nl/subdomains/blog/httpdocs/wp-content/plugins/igsyntax-hiliter/classes/frontend.php on line 510 Warning: ksort() expects parameter 1 to be array, string given in /var/www/vhosts/ansuz.nl/subdomains/blog/httpdocs/wp-content/plugins/igsyntax-hiliter/classes/frontend.php on line 513 Warning: Illegal string offset 'language' in /var/www/vhosts/ansuz.nl/subdomains/blog/httpdocs/wp-content/plugins/igsyntax-hiliter/classes/frontend.php on line 510 Warning: ksort() expects parameter 1 to be array, string given in /var/www/vhosts/ansuz.nl/subdomains/blog/httpdocs/wp-content/plugins/igsyntax-hiliter/classes/frontend.php on line 513 Warning: Illegal string offset 'language' in /var/www/vhosts/ansuz.nl/subdomains/blog/httpdocs/wp-content/plugins/igsyntax-hiliter/classes/frontend.php on line 510 Warning: ksort() expects parameter 1 to be array, string given in /var/www/vhosts/ansuz.nl/subdomains/blog/httpdocs/wp-content/plugins/igsyntax-hiliter/classes/frontend.php on line 513 Warning: Illegal string offset 'language' in /var/www/vhosts/ansuz.nl/subdomains/blog/httpdocs/wp-content/plugins/igsyntax-hiliter/classes/frontend.php on line 510 Warning: ksort() expects parameter 1 to be array, string given in /var/www/vhosts/ansuz.nl/subdomains/blog/httpdocs/wp-content/plugins/igsyntax-hiliter/classes/frontend.php on line 513

General information
There is no out of the box solution from Google to use stronger encryption for the communication between your Android client and a server.

Google provides some information on how to use SSL on the Android developer website titled “Security with HTTPS and SSL“. This site contains two warnings you should not forget.

  1. Do not use a TrustManager that does nothing.
  2. Replacing the HostnameVerifier can be very dangerous.

A reason to use a TrustManager that does nothing could be for local or Alpha testing where you don’t have a valid SSL certificate on the server. Another could be to give QA the option to debug network traffic. If for some reason you do use a TrustManager that does nothing, make sure this implementation can never make it to a production version of the application. One way to do that is only include the empty TrustManager in one of the (testing) application flavors.

If you do want to use a custom HostnameVerifier, use composition to reuse the system’s default HostnameVerifier. This way you can add your own verification and still benefit from the default verification. You should apply the same when building your own TrustManager, that way your validation is never worse than the default system validation.

Pinning certificates
One way to make the encryption stronger is by using pinned certificates. This will help your application protect itself from fraudulently issued certificates. I will explore two ways of pinning a certificate. One is including the actual certificate, the other is to use SPKI or Subject Public Key Info.

Getting the server certificate
Before getting started with either method for pinning a certificate, you need to get hold of the server certificate. The easiest way to optain that would be to ask your system administrator. If that is not possible, you could use OpenSSL or FireFox to just save it from the browser. For more details, see “How to save a remote server SSL certificate locally as a file” on SuperUser.com.

Including the certificate
Start by including the certificate file (as raw resource) in your APK.
After this, implement your own TrustManager that uses the following pseudo-code to analyse the received certificate.

Get the key from the bundled certificate.

  1. FileInputStream fis = new FileInputStream("path_to_pem");
  2. CertificateFactory cf = CertificateFactory.getInstance("X.509");
  3. java.security.cert.Certificate c = cf.generateCertificate(fis);
  4. System.out.println(c.toString());
  5.  
  6. // will get you the public key object you can compare against.
  7. RSAPublicKey pk = (RSAPublicKey) c.getPublicKey();
  8.  
  9. System.out.println(pk.toString());
  10. String s = new BigInteger(1, pk.getEncoded()).toString(16);
  11. System.out.println(s);

Get the server key.

  1. // that gets the public key provided by the server out of the chain.
  2. RSAPublicKey pubkey = (RSAPublicKey) chain[0].getPublicKey();

Compare the two keys.

  1. // Where pk is the one loaded from your app file space.
  2. pubkey.equals(pk);

SPKI
An alternative approach to bundling the certificate with your application is to use the Subject Public Key Info method. This will just store the certificate’s fingerprint instead of a whole file.

To generate the fingerprint for your certificate, follow the instructions in “Appendix A” of the “Public Key Pinning Extension for HTTP” document, example:

  1. openssl x509 -noout -in certificate.pem -pubkey | \
  2.     openssl asn1parse -noout -inform pem -out public.key
  3. openssl dgst -sha256 -binary public.key | openssl enc -base64

You can calculate the same fingerprint in Java using the snippet below:

  1. // Assume the 'certificate' is a X509Certificate.
  2. MessageDigest digest = MessageDigest.getInstance("SHA-256");
  3. byte[] encodedKey = certificate.getPublicKey().getEncoded();
  4. byte[] hash = digest.digest(encodedKey);
  5. String fingerprint = Base64.encodeToString(hash, Base64.NO_WRAP);

Notes
SSL certificates can be invalidated for various reasons (they expire, get compromised, etc). Because of this you should consider showing a message to the user when pinning a certificate fails.

To avoid your app breaking when a certificate gets invalidated, you can keep a list of valid public keys. Start with the first in the list, if that doesn’t work fall back to the next public key in the list.

Update or change a certificate before the previous one expires. Unless the certificate is compromised, the public key will most likely stay the same. (If you use the same private key/CSR.)

Droidcon UK – day 2

Warning: Illegal string offset 'language' in /var/www/vhosts/ansuz.nl/subdomains/blog/httpdocs/wp-content/plugins/igsyntax-hiliter/classes/frontend.php on line 510 Warning: ksort() expects parameter 1 to be array, string given in /var/www/vhosts/ansuz.nl/subdomains/blog/httpdocs/wp-content/plugins/igsyntax-hiliter/classes/frontend.php on line 513

9.00 What’s new in Android

Company: Google, Speaker: Chet Haase

New Nexus 6 and 9 devices. Android Studio 1.0 Beta.

Material design: Tangible surface, easy ways of branding, meaningful motion, adaptive design. Also see the design documentation.

UI toolkit: New theme (material), theme colours (all assets are greyscale and can be tinted), dynamic colors (pallet API). New (material) widgets: RecyclerView, (Stacker)GridView, CardView.

Graphics: Real-time shadows relative to light source (60fps), outlines for Views. Render thread.

Material animations: Activity and Fragment transitions. Animation curves. Animated reveal. Animated vector Drawable.

System changes: Document-centric apps, new (material) Notifications, heads-up Notifications. Notifications on lock-screen.

Media: OpenGL ES 3.0, Android extension pack, Camera & Audio: raw input, MediaSession, MediaBrowser.

ART is now the runtime for L.

Project Volta: optimising battery usage. New service: BatteryStats. Use Historian (on Github) to analyse results.

10.00 Papercraft

Company: Google, Speakers: Chris Banes, Nick Butcher, Slides on G+.

Reasons behind Material Design:

  • Providing a coherent cross-platform experience.
  • A more flexible design system for Android.
  • A rational approach to visual, interaction and motion design.

Tangible surfaces
UI as digital paper. Adding z-depth, signifying UI element importance.

Z = Elevation + TranslationZ.
New “stateListAnimator” XML-attribute.

Extend the ViewOutlineProvider class to create any clipping.

Print-like design
Refined typography, using typography to provide the app structure. Typographic scale provides the standard scales.
There is a new TextAppearance.AppCompat style.

Using bold colours, take the brand colour and use the complementary as accent.
Styling using:

  • colorPrimary
  • colorPrimaryDark
  • colorAccent

Theme.AppCompat provides the tinting as well (API 7+).

Content can provide colours. To generate the colours, use the Palette class:

  1. Palette.generate(bitmap)

The palette generation takes roughly 30ms, so run it on a separate thread.

Meaningful motion
To enable Activity transitions, add “android:windowContentTranstion” attribute to your theme. Next, Define a shared element. And finally, start the Activity.

Asymmetric motion, user initiates motion. To create this, use the RippleDrawable (“ripple” XML-tag).
Circular Reveal, use ViewAminationUtils.createCircularReveal(…).

Adaptive design
Making apps looks good on various screen sizes.
Think in Keylines, Increments, blocks.

New more flexible Toolbar (based off Actionbar).
Add “Toolbar” XML-tag in your layouts. Also available in AppCompat.

12.00 How to Build a One Man Band

Speaker: Nicoll Hunt

You’ll need: Time, money, skillz.

Stop wasting time on unrelated things. Use self-funding and/or crowd funding (like kickstarter). Work with your limitations, accept them, don’t try to fight them. Learn to deal with criticism.

13.45 Graphical Magic – Styling Android

Speaker: Mark Allison, Blog: blog.stylingandroid.com

Increasing performance by reducing GPU overdraw. Turn “GPU Overdraw” on in device developer settings to see trouble areas. Flatten any Views with transparent backgrounds. Hook into the “onPreDraw” method.

Use the ColorMatrix class to manipulate colour information. Use a paint Shader to apply effects on text, the same way you can create outlines (a.k.a image masks).

Applying blur effects with RenderScript. To avoid artefacts, add a margin and crop it off later.

Don’t forget to recycle() any temp Bitmaps.

14.35 Rx-Fy all the things!

Company: Novoda, Speaker: Benjamin Augustin

Reactive Extensions Java project: RxJava on Github.

Important Operators/methods to remember:

  • map
  • flatMap
  • onErrorResumeNext()

To perform multiple operations / create a pipeline, chain multiple of the above Operators.

Novoda working on a set of RxJava tools for Android.

RxAndroid – Collection of tools for Android created by SoundCloud.

For a quick intro into RxJava, have a look at the RxJava workshop in the Novoda workshops repo.

15.45 “Project Volta”
Or “Getting By With Less Than 1.21 Gigawatts”

Company: Commonsware, Speaker: Mark Murphy

Discussing the new JobScheduler class. All slides can be found at commonsware.com/presos/droidconUK2014.

BatteryHistorian is a python script hosted on the Google Github.

16.35 Deep Dive into the Gradle-based Android Build System

Company: Gradleware, Speaker: Etienne Studer

The Gradle DSL configuration is mapped to the AppExtension object.

When creating your own tasks, make sure to define inputs and outputs so the task can be skipped when there is no change.

Enable Gradle daemon on your local machine to cut down VM warm-up times.

17.30 Closing Ceremony

Droidcon UK – Day 1

Warning: Illegal string offset 'language' in /var/www/vhosts/ansuz.nl/subdomains/blog/httpdocs/wp-content/plugins/igsyntax-hiliter/classes/frontend.php on line 510 Warning: ksort() expects parameter 1 to be array, string given in /var/www/vhosts/ansuz.nl/subdomains/blog/httpdocs/wp-content/plugins/igsyntax-hiliter/classes/frontend.php on line 513 Warning: Illegal string offset 'language' in /var/www/vhosts/ansuz.nl/subdomains/blog/httpdocs/wp-content/plugins/igsyntax-hiliter/classes/frontend.php on line 510 Warning: ksort() expects parameter 1 to be array, string given in /var/www/vhosts/ansuz.nl/subdomains/blog/httpdocs/wp-content/plugins/igsyntax-hiliter/classes/frontend.php on line 513 Warning: Illegal string offset 'language' in /var/www/vhosts/ansuz.nl/subdomains/blog/httpdocs/wp-content/plugins/igsyntax-hiliter/classes/frontend.php on line 510 Warning: ksort() expects parameter 1 to be array, string given in /var/www/vhosts/ansuz.nl/subdomains/blog/httpdocs/wp-content/plugins/igsyntax-hiliter/classes/frontend.php on line 513

9.00 Barcamp planning

Getting all sessions in for the day’s talks. At the end of the day there will also be an “Appcamp” to demo applications to the audience.

10.30 AIDE – Android Wear app with AIDE

Company: appfour GmbH, Speakers: Hans Kratz, Dr. Dennis Strein, Website: www.android-ide.com.

AIDE = Android Integrated Development Environment.

Applications that are “Wear enabled” contain the Wear APK inside the phone APK.

AIDE uses Gradle to package Wear. To enable Wear, add the following to your build dependencies:

  1. wearApp project(':wearable')

Google also has a lot of information on how to create wearable apps.

The presentation was followed by a live demo of how to use AIDE on a device.

11.10 Modern Testing Technologies

(or how to avoid getting murdered in your sleep by a death goblin.)

Speaker: Mr Death Goblin a.k.a. Zan Markan

Follow SOLID principles to increase your chances to catch a goblin.

Good tools for this include: Dagger (DI/IoC), Mockito (mocking), Calabash, Robotium, etc. Start using the tools before you write a single line of code.

When your project grows, allow for refactoring. Split up too big methods, classes, etc. The tests should be there to help you achieve that and keep things working.

Use CI tools, like Travis, to automatically test / build your project.

How to deal with legacy projects? Start by covering new features with tests. Cover any code related to bug fixing with tests. Little by little the coverage will get better and better.

12.05 TDD Coverage

Tools: GUnit (Unit tests), Robolectric, Mockito (Mocking), Emma (for coverage).

Performance testing with a monkey that visits every Activity, combine this with TraceView for profiling to measure memory usage, CPU, etc.

Testing the manifest: Use Robolectric to get a shadow application, fetch the package manager, check what service, receivers, etc are registered and verify that they exist.

12.45 Simple persistence with cupboard

Company: LittleRobots, Speaker: Hugo Visser, Project home: bitbucket.org/qbusict/cupboard

SQLite powered, using field names (from Models) to match columns. Simple usage example 

  1. cupboard().withDatabase(db).put(person)

14.20 Calligraphy – Fonts in styling

Company: YoYo, Speaker: Chris Jenkins, Project home: github.com/chrisjenx/Calligraphy

Simplifying using custom fonts on Android.

Example usage:

  1. <TextView ... fontPath="fonts/your_font.ttf">

15.55 Y U No craftsman!?

Company: Novoda, Speakers: Paul Blundell and Xavi Rieau

Ways to create better code / be a better craftsman.

Pair programming, best coding practices, code reviews. Care about CI, show build status (i.e. on a big screen in the office). Run static analysis reports. Test!

To make things more fun: CI Game (Jenkins plugin), creates a monthly leaderboard.

Use the latest tools with your work.

Be “agile”, build features the way they make sense. Believe in YAGNI (you ain’t gonna need it), don’t over-engineer.

Make your app awesome:

  • Get off the main thread.
  • Use Strict Mode (both in code and dev options).
  • Use “GPU Profiling” (under dev options).
  • Use “Show Overdraw”
  • Polish the app. (Lots of tips in the Android docs.)
  • Animate all the things.
  • Listen to (user) feedback.
  • Measure the data.
  • Follow the guidelines.
  • Add debug screen(s) for QA and yourself.
  • Proper versioning.
  • Hexagonal architecture.

16.30 Democamp

Showcasing the following applications

  • SkyScanner
  • DoneDeal
  • VelociCaptor
  • ???
  • Clue
  • See Speak
  • Hey Order
  • Islamic prayer times
  • Kites
  • Stay.com
  • ???
  • E-reader Open Source app

17.30 Practicing Practical Best Practices – for Software Development Practitioners

Company: Google, Speaker: Chet Haase – Process Methodologist

“Practices Make Perfection”

Traditional best practices: Code comments, Naming conventions, Simplicity, Portability. Continuous Integration, Testing, Process.

Laws of software quality:

  1. errors = (more code)^2 = e = mc^2
  2. The more bugs, the less quality.

The path to better quality software: higher quality, less bugs, fewer code.

Android reverse engineering

Warning: Illegal string offset 'language' in /var/www/vhosts/ansuz.nl/subdomains/blog/httpdocs/wp-content/plugins/igsyntax-hiliter/classes/frontend.php on line 510 Warning: ksort() expects parameter 1 to be array, string given in /var/www/vhosts/ansuz.nl/subdomains/blog/httpdocs/wp-content/plugins/igsyntax-hiliter/classes/frontend.php on line 513 Warning: Illegal string offset 'language' in /var/www/vhosts/ansuz.nl/subdomains/blog/httpdocs/wp-content/plugins/igsyntax-hiliter/classes/frontend.php on line 510 Warning: ksort() expects parameter 1 to be array, string given in /var/www/vhosts/ansuz.nl/subdomains/blog/httpdocs/wp-content/plugins/igsyntax-hiliter/classes/frontend.php on line 513 Warning: Illegal string offset 'language' in /var/www/vhosts/ansuz.nl/subdomains/blog/httpdocs/wp-content/plugins/igsyntax-hiliter/classes/frontend.php on line 510 Warning: ksort() expects parameter 1 to be array, string given in /var/www/vhosts/ansuz.nl/subdomains/blog/httpdocs/wp-content/plugins/igsyntax-hiliter/classes/frontend.php on line 513 Warning: Illegal string offset 'language' in /var/www/vhosts/ansuz.nl/subdomains/blog/httpdocs/wp-content/plugins/igsyntax-hiliter/classes/frontend.php on line 510 Warning: ksort() expects parameter 1 to be array, string given in /var/www/vhosts/ansuz.nl/subdomains/blog/httpdocs/wp-content/plugins/igsyntax-hiliter/classes/frontend.php on line 513

Often I am quite curious to see how an app is built and what tools the use under the hood. What libraries do they use, what clever tricks are used, etc, etc. Some companies will blog about this on their corporate site, others don’t. An easy way to figure things out is by reverse engineering the application.

Getting data off the phone
The first thing you need to do is get the application from your phone to your computer.

To do this, you can use the APK Extractor app.

“This application will extracts APK which is installed on android device and copy to SD card.”

From there it is a matter getting the data from the SD card. I normally just use adb pull. Have a look at the adb documentation for more details.

Decompiling
Once you have de application on your computer, there are various tools you can use to reverse engineer it.

The first step though, is to unpack the APK. Luckily this is really easy, as an APK is just a ZIP file. Extract it with your favorite ZIP-tool.

At this point all extracted data is mostly represented in binary form. Opening the AndroidManifest.xml for instance, won’t give you much information yet. This is where the various tools come in.

To “decode resources to nearly original form” you can use apktool. To decompile an application using apktool, run:

  1. apktool d name_of_apk.apk

For any additional options, have a look at the apktool documentation.

Decompiling using apktool will result in a new folder with the same name as the APK. This folder will contain all decoded data. If you open up the AndroidManifest.xml file from there, you’ll see it is now in a human-readable format. All code is decompiled to smali. Smali is disassembled code from the dex format used by Dalvik. It seems to follow the same package and class naming as the original Java code. If you want to learn more about smali, have a look at the links in the answer to “What’s the best way to learn Smali” on Stackoverflow.

If you don’t want to change any code and just want to learn about the application’s inner workings, you can make your life a little easier by using a combination of two other tools: dex2jar and jd-gui.

As the name says, dex2jar will convert a .dex file to a jar. This, again, is a fairly simple process. Running the command below will generate name_of_apk.jar. 

  1. d2j-dex2jar name_of_apk.apk

To explore the jar, open it in JD GUI. The dex2jar process does not guarantee to be able to convert everything. Sometimes you will find conversion errors in the exported code. These are indicated by a line starting with “// ERROR //”, followed by the smali code.

Recompiling
After decompiling, you can make changes to the code, recompile the application and install it on your device.

Make any modifications you want to the code and recompile using

  1. apktool b folder_of_decoded_apk

Next, sign the new application. Google has great instructions on how to sign an application, so I won’t repeat that here.

To install the new application on your phone, run

  1. adb install -r name_of_apk.apk

You will have to uninstall the original version first before you can install your modified one. This is because the version you created is signed with a different certificate.

Word to the wise

Make sure you are not breaking any laws when using reverse engineering. In some countries it is legal, in others it is illegal.

When reverse engineering is legal in the country you live in, make sure the software’s (or application’s) Terms and Conditions don’t explicitly forbid you to reverse engineer.

Even when the above hurdles are overcome, make sure to not blatantly copy and paste someone else’s code.

Android swipe to reveal

Warning: Illegal string offset 'language' in /var/www/vhosts/ansuz.nl/subdomains/blog/httpdocs/wp-content/plugins/igsyntax-hiliter/classes/frontend.php on line 510 Warning: ksort() expects parameter 1 to be array, string given in /var/www/vhosts/ansuz.nl/subdomains/blog/httpdocs/wp-content/plugins/igsyntax-hiliter/classes/frontend.php on line 513 Warning: Illegal string offset 'language' in /var/www/vhosts/ansuz.nl/subdomains/blog/httpdocs/wp-content/plugins/igsyntax-hiliter/classes/frontend.php on line 510 Warning: ksort() expects parameter 1 to be array, string given in /var/www/vhosts/ansuz.nl/subdomains/blog/httpdocs/wp-content/plugins/igsyntax-hiliter/classes/frontend.php on line 513

More and more Android apps seem to use a swipe-to-reveal or swipe-for-action UX pattern with ListViews. This is a nice way to give (power) users fast access to certain actions. One of the downsides is that these swipe gestures are often hard to discover.

If you want to use this technique, have a look at 47 degree’s android-swipelistview library.

I ran into a small issue when trying it out. When I was building my project, I got the following error:

  1. error: Attribute "***" has already been defined

In my case this was caused by ActionBarSherlock using the same library as the android-swipelistview project. Adding an exclusion to my Gradle build script solved this.

  1. compile ('com.fortysevendeg.swipelistview:swipelistview:1.0-SNAPSHOT@aar') {
  2.  
  3.     transitive = true
  4.     exclude group: "com.android.support", module: "appcompat-v7"
  5. }

Usage in combination with SwipeRefreshLayout

If you want this swipe library in combination with the new SwipeRefreshLayout class, there is a little more work you need to do. To facilitate this, I have forked the original project and added the functionality as suggested by Keith Thompson in the issue he opened on the project site.

I ran into another issue where both the swipe-to-reveal as the pull-to-refresh actions were performed. This would happen when the ListView was at the top, the user would swipe horizontally and then pulled down. This has been fixed in my fork too.

An example of how to hook up this functionality can be found in Keith’s fork of the android-swipelistview project. The key classes to look at are “CustomSwipeRefreshLayout” in the sample project and “RefreshSwipeListView” in the library.

Other issues

The original android-swipelistview project has some other issues too:

The fixes for these issues have been committed to my fork of android-swipelistview too.

Privileged Aspects

Warning: Illegal string offset 'language' in /var/www/vhosts/ansuz.nl/subdomains/blog/httpdocs/wp-content/plugins/igsyntax-hiliter/classes/frontend.php on line 510 Warning: ksort() expects parameter 1 to be array, string given in /var/www/vhosts/ansuz.nl/subdomains/blog/httpdocs/wp-content/plugins/igsyntax-hiliter/classes/frontend.php on line 513 Warning: Illegal string offset 'language' in /var/www/vhosts/ansuz.nl/subdomains/blog/httpdocs/wp-content/plugins/igsyntax-hiliter/classes/frontend.php on line 510 Warning: ksort() expects parameter 1 to be array, string given in /var/www/vhosts/ansuz.nl/subdomains/blog/httpdocs/wp-content/plugins/igsyntax-hiliter/classes/frontend.php on line 513

When you are using Aspect-Oriented Programming with AspectJ and you want to get around Java restrictions in your Aspect, you can declare the Aspect “privileged“.

Say you perform some logging from your Aspect, but the member you want to access has no (public) accessor method. You could create a public getter method and use that. Better would be to make the Aspect privileged so it can access the member even though it is declared private. This scenario is demonstrated in the snippets below.

Given the following class “Foo”.

  1. ppublic class Foo {
  2.     private String bar;
  3.  
  4.     private void doSomething() {
  5.         bar = "bar";
  6.     }
  7. }

The Aspect would look something like this.

  1. public privileged aspect FooLogging {
  2.     protected pointcut myClass(): within(Foo);
  3.     private pointcut doSomethingMethod(): myClass()
  4.             && execution(doSomething());
  5.  
  6.     after(): doSomethingMethod() {
  7.         String value = ((Foo) (thisJoinPoint.getThis())).bar;
  8.         // Logging goes here.
  9.     }
  10. }

There is one limitation to privileged Aspects though:

Privileged aspects are not supported by the annotation style.

See “Aspect Declarations” in “Chapter 9. An Annotation Based Development Style” of the “The AspectJ 5 Dev Kit Developer’s Notebook“.

Loading Contact photos with Picasso

Warning: Illegal string offset 'language' in /var/www/vhosts/ansuz.nl/subdomains/blog/httpdocs/wp-content/plugins/igsyntax-hiliter/classes/frontend.php on line 510 Warning: ksort() expects parameter 1 to be array, string given in /var/www/vhosts/ansuz.nl/subdomains/blog/httpdocs/wp-content/plugins/igsyntax-hiliter/classes/frontend.php on line 513

The Picasso image downloading library has an interesting feature that I just stumbled upon. It can load Contact photos based on a passed in Contact Uri containing the ContactsContract.Contacts.LOOKUP_KEY. It is as simple as:

  1. Uri uri = Uri.withAppendedPath(
  2.     ContactsContract.Contacts.CONTENT_LOOKUP_URI, lookupKey);
  3. Picasso.load(uri).into(myImageView);

It doesn’t seem to be mentioned on the Picasso website, but it is a very useful feature.

If you want to know exactly how Picasso loads the Contact photo, have a look at the ContactsPhotoBitmapHunter class.