All about Android |

It is a fact of using a language like Java that your binaries are easily decompiled.
It isn’t possible to avoid decompiling, but you can disguise your sourcecode.

What you need is a code obfuscator.

Obfuscators are basicaly replaces meaningfull class, variable and method names with random meaningless names.
This process makes it harder to understand the decompiled code for attackers.

Short sample:

Decompiled source without Code Obfuscator:

int number0 = 4;
int number1 = 1850;
int output = 0;

private void calc(){
output = number0*number1;
}

Obfuscated and then decompiled source

int xyk5 = 50/10-1;
int un82a= 5550/3;
int cbjes= 0*19;

private void uhmem(){
cbjes = xyk5 * un82a;
}

But Obfuscated code is harder to debug. For example stack traces are also encrypted. You need conversion tables to translate stack traces into their original names.

A good opensource Java Obfuscator with Android support is ProGuard.

Thanks for reading.
Andy

No tags

If you want create an app that should run on all android devices, it is important to handle all the different screen sizes.

1. The Density-independent pixel

A short sample:

We create in our layout a button:

<Button android:id=”@+id/testButton”
android:layout_width=”100px”
android:layout_height=”25px”>

The “testButton” has a height of 25 pixels and a width of 100 pixels.
What would happen if we run this test application on different android devices with different screen solutions?

In the first picture (Low density 120dpi) our button appears bigger, because we have lesser pixels at the same screen area.

The Button in the second picture (Medium density 160 dpi) appears smaller, because the pixel density is higher.

With a high density display the button is 33% smaller than the previus button with 160 dpi. Because there are more pixels at the same screen area.

How can we fix this problem?

The solution is easy:

We must only use the dip (Density-independent pixel) instead of px(Pixel).

The dip is a virtual pixel unit that android application can use to defining a similar User Interface.

The density-independent pixel is equivalent to one physical pixel on a 160 dpi screen or 1 density-indepent pixel is equivalent to 1.5 physical pixel on a 240 dpi.

<Button android:id=”@+id/testButton”
android:layout_width=”100dip”
android:layout_height=”25dip”>

2. The layout

For a perfect Layout you should use the RelativeLayout instead of AbsoluteLayout.

With an AbsoluteLayout you define an exact position for each element. So, it is impossible to handle a similar UI for different screen sizes.

Therefore, you should use a RelativeLayout to design a uniform User Interface.

No tags

Aug/10

12

Canvas – How to render large Bitmaps?

My strategy game uses a large background image ( > 1000px x 1000px).
Canvas must render the full texture each frame! But a mobile phone can not display the full texture. So, that methode costs a lot of cpu time. Thats horrible!

The solution for this problem is easy:
Why should we render parts of the background image that a user can not see!

My solution:

//scrollingPositionX == Position on Map X
//scrollingPositionY == Position on Map Y
//canvas.getWidth()  == Width of the viewport
//canvas.getHeight() == Height of the Viewport

Rect rect1 = new Rect(scrollingPositionX, scrollingPositionY, scrollingPositionX + canvas.getWidth(), scrollingPositionY + canvas.getHeight());
Rect rect2 = new Rect(0, 0, canvas.getWidth(), canvas.getHeight());

canvas.drawBitmap(largeBitmapTexture, rect1, rect2, new Paint());

First, we create a rectangle with the part of the bitmap which we want to display.
Than we create a second rectangle with the viewport dimension.
Last, the Canvas methode drawBitmap can handle this two Rectangle and we have a very performant way to render large Bitmap.

Thats simple but very effective, because we render only visible pixels of the bitmap!

No tags

Jul/10

17

Java performance tips

I am working on an strategy game for the android platform and therefore i want tell you some performance tipps.

This tips should you help to make your games a little bit smoother.

First rule
Performance optimisations should not never do at the end of a coding project. A high performance is very important and should get a high priority from the outset.

Threads
Your main loop will need to run on its own thread.  Android has a main UI thread and if you don’t run your own thread, the UI thread will be blocked by your game which will cause the Android OS to not be able to handle any of its normal update tasks

Use benchmarks
You should always measure performance and use the Log class to evaluate the benchmarks results.

Correct loops
Two possible loops:

public void first() {
for (int i = 0; i < yourArray.length; ++i) {
// FIRST LOOP – CODE
}
}

public void second() {
int len = yourArray.length;
for (int i = 0; i < len; ++i) {
//SECOND LOOP – Code
}
}

First loop is slowest, because  the cost is to expensive of getting the array length once for every iteration through the loop.

Second loop is faster, because with this methode we are avoiding the lookups (Array.length).

Avoid Getters and Setters
Virtual method calls are expensive and costs cpu time, much more so than simple instance field lookups. It looks dirty but its faster (3x – 7x)!

Object creation
Avoid unnecessary object creation and therefore do not initalize local variables. Make all variables and objects public. That has the result that the garbage collection must never run. The runtime of the garbage collection costs 150-400ms! It will also pause all other threads and would run every 4 – 7 seconds.

General tips
Declare variables final if they are not modified after being initialized.
‘==’ is faster than equals().
Use StringBuffer instead of +.
Make classes final.
Avoid unused code inside loops and use “breaks”.
switch is faster than a complex if-else construction.
Avoid loading (import) classes you do not need.

Important:
You should keep clearly in mind that these tips helps nothing when you are using a bad design!

Thanks for reading.

Andy

No tags

Jun/10

24

13 facts why Android is better than iOS!

I thought its time to write down some facts why Android is better than iOS!

My advice, should you be an Apple Fanboy, Apple Lover,  Apple fanatic or Steve Jobs, I would you not recommend to read further. Because you dont want to read it.  But should you have interests in other mobile platforms such as Symbian, WebOS, Windows Mobile User or Android, then you should read further.

WHY ANDROID IS BETTER THAN IOS4

1st Android is open and free
The new iOs4 version is not compatible with the first generation of iPhones, and does not appear on older Apple products! That is a fact. Android is open and a great Android OS developer community is active and works hard to make Android better. This great community is the reason why Froyo will be released  on the oldest Android devices. There is no fragmentation on the Android platform!

2nd Its more open
There was an app in the app store. This app was a little “home screen” app with some additional features than the standard homescreen. But Apple removed this app from the market. Apple does not want alternative homescreens. In the Android Market there are a lot of different home screens. Manufacturer like HTC and Sony Ericsson sells their Android device with his own surface. You dont like the surface? Thats not a problem! You can easily install other surfaces.

3rd Multitasking
Shortly, there was a report that tests the implementation of multi-tasking in different mobile os platforms.

The solution is obvious. WebOS has the best implementation of multi-tasking. The second place got Android. iOS got the last place.
The reasons are simple, because the multitasking implementation in iOS is very restricted. Some people calls the multitasking feature in iOS also fake-tasking.

4th Google Integration
All Google products are pre-installed. For example: Gmail, Talk, Maps, Goggles, calendar, search and Youtube.
You can of course replace the google products through alternative apps that you can download in the android market.

5th Usability
Android offers more options for personalization.
Short sample:
You can  move Widgets on the homescreen and folders can be created. You could also change: wallpapers(live wallpaper), boot screens, lockscreen, themes and so on. You have full access on the filesystem and you can create links.

6th Choose your hardware
HTC, Motorola, Sony Ericsson, Samsung, LG sells Android phones. With this great range of hardware you can find your personal android phone with your budget and hardware requirements.

7th Flash Support
Android 2.2 supports official Flash 10.1.  Steve Jobs told us that Flash will never appear on iOS.

8th App Market
The App Store from Apple has more apps than the Android Market. But whats the meaning of the developer about this two stores? Apps for the App Store will only published if Apple says “YES”. Apple investigates if an app corresponds all the Apple guidelines.

Even the layout: Apps, Button color and so on are prescribed. Android App developers have significantly better. In other words, there are no guidelines for android apps.

9th Synchronization
Google phones come without a synchronization software such as iTunes.
There is also a support for microsoft outlook, thunderbird and so on.

10th Extended memory
Almost all Android smartphone have memory card readers. iPhone fans wait in vain for.

11th Replaceable battery
In all Android devices, you can easily change the battery without any problems.
The iPhone must send to the support. That costs additional money.

12th Updates
If you want to update the iPhone OS you must know, that you must connect it to a PC to start the update process.
Android updates comes via the Internet (OTA, Over The Air) directly on the Android phone.

13th Warranty
The most iPhone User do at first jailbreak. Because whitout jailbreak they could not do anything ;)
But with this step they will loss the warranty. Android Users do not know this problem.

Yesterday, I found this amusing video :)

Have fun…

Thanks for reading.
Andy

No tags

This is the third article of my little blog serie “How does android work?”.
Now, in this article i want to explain the operation of the memory management in Android.

First of all, many people say “Why can i not close an app? It does need memory and its very unperformant”.
Yes if the person is a windows user the statement would be true. The more apps are running the merrier lesser memory is free.
In android the memory management does automatical kill “old” processes to reclaim resources.

If you close an application, the application will switch in the background (Idle) mode. The state of the current running activity will be saved to the system process.
Then you start some more apps the memory managament detects automatical if the free memory is to “less” and terminates old process automatical. Thats the reason why Android doesnt need a swap file and users must not close applications.
Throughout the termination of the app process we get more memory resources and can start the new activity (process).
Android keeps a LRU (last recently used) list and starts killing the oldest unneeded process if memory needed.

An another effect of the LRU is, that the user can go backwards. For sample: You read a mail and click a link. The browser will be opened. From the Browser there is a videolink for youtube. The youtube app starts. Then the youtube video is over you can go back with the backward buttons and you are realy fast in your mail application back.

The advantage is, that the “closed apps” while they are running in background doesnt need any cpu time and also so no battery power. But yes, they need memory resources.

Android OS Developer could be interested the “lowmemorykiller.c” file in the directory “drivers/misc“. In the kernel source file you could set up exact memory rules for the memory manager.

If you are know interested and want to see your current memory setting, take a look there: /sys/module/lowmemorykiller/parameters/minfree

On my HTC Hero the settings are: 1536,2048,4096,5120,5632,6144

These 6 values (unit pages) are memory limits for different kind of applications when the memory management starts killing processes.

The advantage to change memory setting directly in kernel is that you don t need a special task killer app which must run allways in background!

If you search for “Android and Memory” there are a lot of different meanings about the possible truth of memory management in android.

If you have any questions or want tell me anything please leave a comment.

Thanks for reading.

Andy

No tags

What makes the JIT Compiler Froyo so fast!

The guys from AndroidPolice.com could test froyo on the nexus one. They could test so the official JIT Function which is new in the froyo used Dalvik Virtual Machine.
The JIT Function should speed up the code execution speed. First Benchmarks from the guys confirmed my presumption.
So, how faster is Froyo? Mhh not realy faster… Only 450%!!

First, check out the Benchmarks result which was made with a tool called Linpack.

6.7 MFLOPS is an average value with 2.1 running on an Nexus One.
37.6 MFLOPS gets an Nexus One with the brandnew Froyo JIT Function.
IN Total 450 % faster. Thats awesome!

What makes an JIT Compiler so fast?
First, i want explain the differences.
With older Android versions (< 2.1), apps will compile all the code to machine language bevore the program runs.
With the JIT Function apps will be compiled in realtime. So the JIT Compiler runs after the program has started and compiles the code on the fly(just-in-time).

The reason why the JIT Function is so fast is realy easy:
The JIT Compiler knows things about the code and the hardware that an traditional Compiler could never know.

Short sample:
You define a normal variable within a code block. The compiler detect (on the fly) that the variable looks like an constant (at this moment). With this simple knowledge the JIT Compiler makes some performance optimizations. Thats a small sample. The JIT Compiler which is working in Froyo has some more optimisation features. Normal performance boosts are between 2x and 5x speed.

If you want to know more about the procedure, take a  look at the close world assumption.

Also, the jit compiler is able to collect statistics about how the application is actually running and it can recompile for the best performance.

Now, i hope you have a little bit learned how an JIT Compiler works and why it is sooo fast.

If you have any questions or want tell me something, please leave a comment ;)

Thanks for reading.

Andy

No tags

Hello All,

this is the second part of my Android Serie “How does Android Work?”.
In the first part i talked about the boot sequence.

In this second part i want to talk about the fundamental building of Android.

At first, i will show you this picture (it makes it easier to understand ;) )

You can see that there are 4 layers.

1. Linux Kernel

At the Bottom there is the Linux Kernel (2.6). The Kernel is the Hardware Abstraction Layer(HAL).
If you want port Android on an other Device the first thing you must do is to update and modifiy the drivers.
Because the drivers are necessary that the OS can communicate and manage hardware pices. (Display Driver, USB Driver …)

2. Libraries
Above the Kernel there is the Android Native libraries. It is written in C and C++.
There are interfaces so you have access with Java at this libraries.

The components of the libraries:

  • Surface Manager composing different drawing surfaces on the screen. Drawing the windows from apps.
  • OpenGl ES used for 3d rendering.
  • SGL used for 2d graphics rendering.
  • Media framework include all necessary media codecs (aac,mpeg and so on).
  • free type used to rendering fonts.
  • SQLite is a relational database system used to store data
  • Webkit is a open source browser engine.
  • libc is the normal C library


2.1 Android Runtime

At next there is the Android Runtime area which includes the core libraries and the dalvik virtual machine.
The Dalvik virtual machine is a Java VM which runs dex files. Which compiled from class and jar files.
The big advantage of dex files is that you get more efficience code which need lesser memory and cpu ressource (-> longer battery lifetime).
The Core libraries are written in Java. It contains all classes you need (IO as sample)

3. Application Framework

The application framework is a toolkit that all application uses.

The components of the framework:

  • Activity Managers manages the livecycle of applications.
  • Package Managers manage what applications are installed. Also responsible for app updates from the market (Android > 2.x).
  • Windows Managers manages windows through the surface manager interface.
  • ContentProviders makes it possible that app could share data with other apps (as sample contacts).
  • Resource Manager is a place where external parts of apps will there be stored.
  • View System,  mainly used for layout management: buttons, list view…
  • Notification Manager notifications through the infobar,
  • Location Manager handles gps informations.

4. Application Layer

The Application Layer is the last layer which is based and supported from the layers below.
There are running all the applications.

That was the second part.
At the next part i want to write something about  the memory management of Android. If you have any questions or want to say anything about this topic please leave a comment. Thank you for reading :)

Ciao
Andy

No tags

This is the first in a series which I want you to explain how does Android work.
In this first part, I would like to explain how the boot process on Android works.

Let’s start:

By pressing the power button, the mobile phone gets energy. This starts the cpu and hardware sided code into the cpu is executed.

This code checks and define the boot sequence. This order is now processed. If a boot loader exists on the partitions it is loaded into RAM.

The boot loader starts now a boot script which provides basic functions. For example, file system, partitions, RAM.

The basic system is now loaded. Now it is time to load the Linux kernel into RAM.

The Linux kernel initialize interrupt controllers, memory creates protections, scheduling and so on.

The last step in the boot process is loading the init process (system/core/init). The init process is process as in any linux based operating system, the first process. It has, therefore, the process id 1. All other processes are started which are then subordinated to this.

If the init process is terminated so the operating system shut down. (At least try to). After the init process there will loading the following processes:
- kthreadd (kernel thread daemon)
- ksoftirqd/0 (Softirq daemon)
- events/0 (events threads process)

Now, the init process will parse the init script which is called init.rc. To put it simply contains the script init.rc all required start parameters.
Necessary parameters are for example details about the system path and storage informations (sd-card)
Now the service processes will be started.

The init process started and the initialize  the Dalvik VM. The first Java component which is running into the Dalvik VM is the system server.
The system server starts all other Android service. For example, telephony manager, gsm manager, bluetooth.

After the system has all servcie successfully launched, it sends a broadcast standard action (ACTION_BOOT_COMPLETED)

If your app to be started automatically must be implemented here, a corresponding broadcast receiver.

That was the first part.
At the next part i want to write something about  the fundamental structure of Android. If you have any questions or want to say anything about this topic please leave a comment. Thank you :)

See you soon
Andy

No tags

Jun/10

18

The future of Android

Android devices are now be 1.5 years at the market. The development of the mobile phone market and the android market was very rapid and good for android last months ago.
But what will happen in the future?
First, on 19 May is expected that google will  introduce officially Froyo.
Froyo is based on the Linux kernel 2.6.32 and supports the JIT compiler and (officially) Flash 10.1.
The development of the operating system is absolutely fast.
But what are the producers that currently deliver Android devices?
Samsung develops its own mobile os which is called Bada.
HTC and Acer announced at least one to the future its own operating system could not be excluded.
Is this the trend? Each manufacturer develops its own operating system again?
In my opinion, it would be very pity. Now, we have a very well functioning operating system what a great community is constantly evolving. Is this great community are divided again?
What do you say about the future of Android?
Let it me know:)

Ciao
Andy

No tags

Older posts >>