ZionSoft     About     Archive     Feed     Privacy

Play with Google Play Services 3 - Map

If you haven’t set up Google Play services yet, please follow this tutorial.

Get Maps API Key

First, create a project for your app in Google Developers Console, and enable Google Maps Android API v2.

Then get you the signing certificate’s fingerprint:

# displays fingerprint of your debug certificate
keytool -list -v -keystore ~/.android/debug.keystore -alias androiddebugkey -storepass android -keypass android
# displays fingerprint of your release certificate
keytool -list -keystore <your keystore>

Then use the SHA-1 fingerprint and your app’s package name to generate a new key for API access from Google Developers Console.

Update AndroidManifest.xml

Now update your app’s AndroidManifest.xml file, specifying the permissions, feature required, and the map key:

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>

Add a Map

The easiest way to show a map is to add a MapFragment (or a SupportMapFragment for older devices) to your activity. Another approach is to add a MapView to your activity or fragment.

To add a map view showing satellite maps with an XML file:

<?xml version="1.0" encoding="utf-8"?>
        map:mapType="satellite" />

Then in your activity:

public class MainActivity extends Activity {
    private MapView mMapView;
    protected void onCreate(Bundle savedInstanceState) {
        // if you use a map fragment, it will take care of its life-cycle management
        // if you use a map view, you need to forward all the following events to it
        mMapView = (MapView) findViewById(R.id.map_view);
    protected void onResume() {
    protected void onPause() {
    protected void onDestroy() {
    protected void onSaveInstanceState(Bundle outState) {
    public void onLowMemory() {

GoogleMap Object

Once you have the map ready, you can use the getMap() method (or the getMapAsync() to get reference to the map asynchronously) of the map view or fragment to get a GoogleMap object. If this method returns null, it means the map is not ready yet (e.g. because the Google Play services is not available). It serves as the entry point for interactions with the map:

  • To configure the UI, e.g. show / hide my location button, enable / disable gestures, use the UiSettings object fetched using GoogleMap.getUiSettings() method.
  • To convert between coordinates on the map and the location on the screen, use the Projection object fetched using GoogleMap.getProjection() method.
  • You can uses GoogleMap.setMyLocationEnabled() method to show or hide the blue dot representing device’s current location, but to get the current location you should follow my previous tutorial on locations.
  • To listen to map click events, you can simply set the corresponding listener using GoogleMap.setOnMapClickListener() or GoogleMap.setOnMapLongClickListener() method.
  • You can set the camera (i.e. which part of the map should be shown) using the GoogleMap.animateCamera() (with animation) or GoogleMap.moveCamera() (no animation) method. To listener to camera changes (e.g. triggered by user), you can specify the corresponding listener using GoogleMap.setOnCameraChangeListener().

Also, you can set map types (normal, satellite, etc.), enable / disable indoor maps, 3D buildings, etc. using the GoogleMap object.

Markers and Info Windows

Markers can be used to indicate locations or other important information on the map, with more detailed information shown in the info window.

The following snippet adds a marker with a custom icon to the map, and displays a default info window showing “Hello, Helsinki!”:

protected void onResume() {
    mGoogleMap = mMapView.getMap();
    BitmapDescriptor bitmap = ...
    Marker addedMarker = mGoogleMap.addMarker(new MarkerOptions()
        .position(new LatLng(60.1708, 24.9375))
        .title("Hello, Helsinki")

One thing to note when using e.g. BitmapDescriptorFactory is, you might need to use MapsInitializer to explicitly initialize the map.

To remove a marker, you can use the Marker.remove() method, or the GoogleMap.clear() method to remove all added markers, shapes, etc.

If you want to animate a marker on the map (e.g. use a custom marker to indicate current location instead of the boring blue dot), all you need is simply update its position periodically using the Marker.setPosition() method.

When the user clicks on a marker, by default it shows an info window with some title and snippet defined when the marker was added. But you can also listen to the click event:

mGoogleMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
    public boolean onMarkerClick(Marker marker) {

If the onMarkerClick() method returns true, it means the click event has been consumed. Otherwise, if false is returned, it will execute the default behavior, i.e. moving the camera to the marker, and showing the info window.

To provide a customized info window:

mGoogleMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
    public View getInfoWindow(Marker marker) {
        // this will be first called
        // the returned view will be used as the entire info window
    public View getInfoContents(Marker marker) {
        // this will only be called if getInfoWindow() returns null
        // the returned view will be used inside the default info window frame

The info window is rendered as an image. It means any subsequent changes won’t be visible unless you re-open the info window, and the info window can only listen to one click event for the whole info window.

Circles, Polygons, and Polylines

To add those shapes to the map, you basically follow the same pattern:

Circle addedCircle = mGoogleMap.addCircle(new CircleOptions()
    .center(new LatLng(60.1708, 24.9375))
// when adding a polygon, the system will automatically connect the
// last coordinate to the first one
Polygon addedPolygon = mGoogleMap.addPolygon(new PolygonOptions()
    .add(new LatLng(60, 24), new LatLng(61, 24), new LatLng(61, 25), new LatLng(60, 25));
// the system won't automatically connect the coordinates
// thus you can see the difference compared to the above polygon
Polyline addedPolyline = mGoogleMap.addPolyline(new PolylineOptions()
    .add(new LatLng(60, 24), new LatLng(61, 24), new LatLng(61, 25), new LatLng(60, 25));

Ground and Tile Overlays

The main difference between these two overlays is: the ground overlay provides a single image for a fixed location on the map, while the tile overlay provides a set of images for different locations at different zoom level on the map.

To add a ground overlay:

GroundOverlay addedGroundOverlay = mGoogleMap.addGroundOverlay(new GroundOverlayOptions()
    .anchor(0.5, 0.5)
    .position(new LatLng(60.1708, 24.9375), 100, 100));

To add a tile overlay:

TileProvider tileProvider = new TileProvider() {
    public Tile getTile (int x, int y, int zoom) {
        // a Tile object consists of raw image data, as well its width and height
        // the map is divided into a 2^zoom x 2^zoom grid
        // for each grid, the system targets 256 x 256 dp
        // if TileProvider.NO_TILE is returned,
        // it means you don't want to provide tiles yourself
        // if null is returned, it means the tile could not be found now,
        // and will be tried again later
TileOverlay addedTileOverlay = mGoogleMap.addTileOverlay(new TileOverlayOptions()

That’s it for today. Happy hacking and keep reading :)

Play with Google Play Services 1 - Set Up

Google has offered a bunch of services that developers can use in their Android apps. In this and following few blog posts, we demonstrate how easy it is to use them. Now, let’s get everything setup.

Download the SDK

You can find Google Play services in the Extras section from your Android SDK Manager. Simply install it. If you also want to support Froyo (Android 2.2), also install Google Play services for Froyo.

After installation, you can find it at */extras/google/google_play_services/*.

Configure Your Project

Update the build.gradle file of the corresponding module, adding the following section:

dependencies {
    compile "com.google.android.gms:play-services:4.1.32"

Then, update the AndroidManifest.xml file of the module, adding the following section:


Check If the Device Has Google Play Services

Considering the variety of Android devices out in the market, it’s possible that the device doesn’t have the latest version of Google Play services you required, the user disables it, or it can be simply missing from from the device. Therefore, it’s best practice to check its availability:

protected void onResume() {
    // code that doesn't require Google Play services
    if (!checkGooglePlayServices())
    // code that requires Google Play services
private boolean checkGooglePlayServices() {
    int result = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
    if (result == ConnectionResult.SUCCESS) {
        // the device has the latest Google Play services installed
        return true;
    } else {
        Dialog errorDialog = GooglePlayServicesUtil.getErrorDialog(result, this, 8964,
            new DialogInterface.OnCancelListener() {
                public void onCancel(DialogInterface dialog) {
        if (errorDialog != null) {
            // the problem can be fixed
            // e.g. the user needs to enable or download the latest version
        } else {
            // for some reason, the problem can't be fixed
            // you should provide some notice to the user
        return false;
protected void onActivityResult (int requestCode, int resultCode, Intent data) {
    // you don't have to check it here,
    // since the onResume() callback will be invoked anyway
    if (requestCode == 8964) {
        // this is invoked when user finishes operation
        if (resultCode == Activity.RESULT_OK) {
            // problem fixed, now you can use Google Play services
        } else {
            // problem not fixed, e.g. user decides not to install the latest version
    } else {
        super.onActivityResult(requestCode, resultCode, data);

Tip: You should make your app usable and requires it only when needed, if Google Play services is not a must-have feature.

Yep, that’s it. Now you have Google Play services ready, have fun with it and keep reading ;)

Go’s defer statement in C++

The Go language provides a useful defer statement to guarantee certain code is always executed when returning from the current scope. Though we can use constructor in C++, things get tricky e.g. when a pointer needs to be deleted. Here we present some simple draft code to solve this issue.

#include <functional>
// the user should fill copy and move constructors
class DeferredAction
    DeferredAction(const std::function<void(void)>& deferred) : m_deferred(deferred) {}
    ~DeferredAction() {
        if (m_deferred)
    std::function<void(void)> m_deferred;

Then if the client code looks like the following:

#include "deferredaction.h"
#include <iostream>
int main()
    DeferredAction deferred([] () {
        std::cout << "executed when the 'deferred' object is destructed" << std::endl;
    std::cout << "print some random stuff here" << std::endl;
    return 0;

It will first print the line: print some random stuff here. Then when the deferred object is destructed when main() returns, it prints the second line: executed when the ‘deferred’ object is destructed.

Displaying Images Efficiently on Android

In this blog post, we demonstrate some simple ways to efficiently display images.

The Straightforward Approach

The simplest way to load an image (e.g. from resource), is to load it in an AsyncTask, and updates the ImageView in onPostExecute():

class ImageLoadingTask extends AsyncTask {
    ImageLoadingTask(Resources resources, ImageView imageView) {
        mResources = resources;
        mImageView = new WeakReference(imageView);
    protected Bitmap doInBackground(Integer[] params) {
        return BitmapFactory.decodeResource(mResources, params[0]);
    protected void onPostExecute(Bitmap result) {
        final ImageView imageView = mImageView.get();
        if (imageView != null)
    private final Resources mResources;
    private final WeakReference mImageView;

This works fine until you try to load some large image, when the image refuses to be loaded with this error from logcat: W/OpenGLRenderer﹕ Bitmap too large to be uploaded into a texture (4000×3726, max=2048×2048)

And of course, it might even throw an OutOfMemory error on low-end devices.

Load a Scaled Image

To solve the problem, we should request the decoder to subsample the original image, as shown below with the updated doInBackground():

protected Bitmap doInBackground(Integer... params) {
    // extracts the size of the original image first
    final int resourceId = params[0];
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeResource(mResources, resourceId, options);
    // calculates the inSampleSize
    if (options.outWidth > mTargetWidth || options.outHeight > mTargetHeight) {
            = Math.min(Math.round((float) options.outWidth / (float) mTargetWidth),
                Math.round((float) options.outHeight / (float) mTargetHeight));
    // decodes the image
    options.inJustDecodeBounds = false;
    return BitmapFactory.decodeResource(mResources, resourceId, options);

This works pretty fine in most cases, until the ImageView is used e.g. inside a ListView, which recycles child views for performance reasons. In this scenario, each time the ImageView is displayed, it will trigger an image load task. However, the sequence when the tasks are finished is undefined. So there is a chance that the image displayed actually comes from the previous item, which for some reason takes longer to load.


To solve this issue, the ImageView should remember the last image it’s supposed to load, so we extends the class and introduces a simple loadImageResource() method as below:

public void loadImageResource(int resId) {
    // if loading or already loaded the same resource, do nothing
    // otherwise cancel the current loading task
    if (mResId == resId)
    if (mImageLoadingTask != null) {
        final ImageLoadingTask loadingTask = mImageLoadingTask.get();
        if (loadingTask != null)
    mResId = resId;
    setImageBitmap(null); // or some placeholder image
    final ImageLoadingTask loadingTask = new ImageLoadingTask(getResources(), this);
    mImageLoadingTask = new WeakReference(loadingTask);

Cache Images

Now everything works fine, except that whenever our ImageView get recycled, it needs to load the image again, so we introduce a simple image cache:

public class ImageCache extends LruCache<Integer, Bitmap> {
    public ImageCache(int maxSize) {
    protected int sizeOf(Integer key, Bitmap bitmap) {
        // uses byte sizes of the bitmaps
        return bitmap.getRowBytes() * bitmap.getHeight();
// sample code to create an ImageCache using 1 / 8th of the memory
final int cacheSize = (int) (Runtime.getRuntime().maxMemory() / 8L);
ImageCache imageCache = new ImageCache(cacheSize);

With the above simple ImageCache, one can easily caches images in memory, and improves the performance significantly.

Forward Secrecy

Traditionally, when someone sends a message, the message is encrypted using the receiver’s public key (or by a session key which is encrypted by the receiver’s public key). It looks secure at first glance, since only the receiver can decrypt the message with the private key. However, if an attack is able to record all the exchanged messages, and somehow obtains the private key at some point in the future, he can decrypt all the recorded messages. To solve this kind of issue, here comes the so called forward secrecy.

With forward secrecy, the attacker won’t be able to decrypt any messages recorded, even if peers’ private keys are compromised at some point in the future. To achieve this, instead of encrypting all the messages using the same key, peers would negotiate a session key through an ephemeral key exchange (e.g. Diffie–Hellman key exchange).

Forward secrecy in action

The following uses OTR as an example to illustrate how forward secrecy is achieved.

  1. When Alice wants to start a conversation with Bob, she picks a random value x<sub>1</sub>, computes A=g^x<sub>1</sub>, and sends her half of key exchange message A, Sign<sub>k<sub>A</sub></sub>(A) to Bob.
  2. Upon reception, Bob picks a random value y<sub>1</sub>, computes B=g^y<sub>1</sub>, and sends his half of key exchange message B, Sign<sub>k<sub>B</sub></sub>(B) back to Alice.

At this point, both Alice and Bob can compute the session key s=Hash(B^x<sub>1</sub>)=Hash(A^y<sub>1</sub>), and they both can also verify the messages are from the correct peer with the attached signature.

Moreover, since the session keys are not associated with the peers’ long term public / private key pairs, the attackers won’t be able to decrypt the messages even if he somehow obtains the private keys in the future. OTR takes one step further by starting a new key exchange on each message sent in a conversation and discarding the old session key once a new one is negotiated, to reduce the possible time window for attacks.

Forward secrecy, asynchronously

As one can easily notice, the above method works perfect in any synchronous environment, where several handshake messages need to be exchanged before any real messages can be sent. This is not an ideal situation e.g. for emails where users exchange mails asynchronously, or mobile platforms where users are not always online.

To tackle with this issue, Moxie proposed a simple trick.

  1. Upon registration, Bob generates 100 signed key exchange messages (called “prekeys”), and sends his half of key exchange messages for each prekey to the server.
  2. When Alice wants to start a conversation with Bob, she connects to the server and fetches Bob’s next prekey.
  3. Alice generates her half of key exchange message, computes the session key using the fetched prekey, and encrypts the text.
  4. Alice sends the message to Bob, which includes the ID of the fetched prekey, her half of key exchange message, and the encrypted text.
  5. When Bob reads the message later, he can computes the session key and decrypt the message.

With this setup, the peers don’t need to be online at the same time, and forward secrecy is guaranteed by the fact that the server never sends out the same prekey twice, and client never accepts the same prekey twice.

Hybrid Application Using QML and Qt C++

Though QML provides a nice way to design user interfaces, and JavaScript is employed there to implement the application logic and works pretty nice in many cases, we might still need Qt C++ in some situations (well, at least JavaScript has limited access outside its sandbox).

integrate QML into Qt C++

Suppose we have a QML file, named myqml.qml, like this:

// this line should be "import QtQuick 1.0" since Qt 4.7.1
import Qt 4.7
Rectangle {
  id: myRectangle
  width: 800
  height: 480
  color: "lightgray"
  Text {
    id: myText
    text: "I love hybrid application!"
    anchors.centerIn: parent
    font.pointSize: 28
    font.bold: true

One easy way to integrate is to use the QDeclarativeView class, which provides a widget to display QML files. You just need the following three lines:

QDeclarativeView view;

However, QDeclarativeView consumes more resources than normal widgets. Fortunately, we can integrate QML into a graphics scene. The following lines shows the basic usage:

// provides an environment for instantiating QML components
QDeclarativeEngine engine;
// encapsulates a QML component definition
QDeclarativeComponent component(&engine, QUrl::fromLocalFile("myqml.qml"));
// creates the graphics item for QML at the engine's root context
QDeclarativeItem *item = qobject_cast<QDeclarativeItem *>(component.create());

Then with the help of the QDeclarativeItem class, you can easily access the properties of the QML element, e.g.:

qDebug() << item->property("color").typeName();
item->setProperty("color", QColor(255, 255, 255));

exposing Qt C++ objects to QML

You can also expose native Qt C++ objects to QML through QDeclarativeContext:

QDeclarativeContext *context = engine->rootContext();
context->setContextProperty("textFromQt", QString("I love hybrid application!"));

Then in QML, you can have e.g. the following line to access them:

text: textFromQt

You can also use QDeclarativePropertyMap to manage the exposed properties:

QDeclarativePropertyMap map;
map.insert("key1", "value1");
map.insert("key2", "value2");
context->setContextProperty("map", &map);

In a QML engine, there could be a couple of contexts, forming a tree structure. The child contexts inherit properties in the parent context. By default, there is only one root context, but you can always add more to give finer control of the exposed data, i.e. different QDeclarativeComponent inside the same context have the same exposed data set.

To expose a self-defined object, we can use the following code:

// define a class with properties
class MyObject: public QObject
  // the NOTIFY signal is needed to inform about changes
  // all properties will be exposed to QML
  Q_PROPERTY(QString text READ text WRITE setText NOTIFY textChanged)
  MyObject(QObject *parent = 0) : QObject(parent), m_text("I love hybrid application!") {}
  QString text() const { return m_text; }
  void setText(QString &text)
    m_text = text;
    emit textChanged();
  void textChanged();
  QString m_text;
// then just expose it so QML can access it through name "myObject"
engine->rootContext()->setContextProperty("myObject", new MyObject());

Moreover, we can create new QML types:

// define the new type
class MyType : public QDeclarativeItem
  MyType(QDeclarativeItem *parent = 0) : QDeclarativeItem(parent)
    setFlag(QGraphicsItem::ItemHasNoContents, false);
  void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget = 0)
    QPen pen(QColor(100, 100, 100), 2);
    painter->drawLine(0, 100, 100, 100);
// then register to expose it
qmlRegisterType<mychart>("net.zionsoft.mytype", 1, 0, "MyType");

In QML, you can use it like this:

import net.zionsoft.mytype 1.0
MyChart {
 id: myChart
 width: 100
 height: 200

Now let’s jump to invoke a Qt C++ function from QML. Basically, QML can invoke slots and functions declared with Q_INVOKABLE. Suppose we have the following function in MyObject:

Q_INVOKABLE void showMessage()
  QMessageBox::information(NULL, "My Test", "Invoking a native function ;)");

Then you can invoke it in QML:


write plugins as QML extension

The benefits for using plugins as QML extensions are similar to using shared libraries, and it can be easily achieved with the help of QDeclarativeExtensionPlugin. Let’s reuse the MyType class defined in the previous section.

First, we need to create a plugin:

class MyPlugin : public QDeclarativeExtensionPlugin
  void registerTypes(const char *uri)
    qmlRegisterType<MyType>(uri, 1, 0, "MyType");
Q_EXPORT_PLUGIN2(myPlugin, MyPlugin);

Then create a file named qmldir to define which plugin to load from where (suppose the plugin is called myplugin):

plugin myplugin /path/to/plugin

Now we can use qmlviewer to launch the QML file:

// no need to import now
MyChart {
 id: myChart
 width: 100
 height: 200


  • Use QDeclarativeView or QDeclarativeComponent to integrate a QML file into native Qt C++.
  • Qt C++ can access the properties of QML elements through QDeclarativeItem.
  • Expose native objects to QML through QDeclarativeContext.
  • New QML types can be exported through qmlRegisterType.
  • The properties of native objects are exported as properties, and the slots or functions declared with Q_INVOKABLE can be invoked in QML.
  • Create plugins for extension using QDeclarativeExtensionPlugin.

SSL Renegotiation Vulnerability Exploited

The SSL renegotiation vulnerability revealed earlier this month has been demonstrated by a Turkish grad student, named Anil Kurmus, to steal user names and passwords of Twitter. The code is also available in the wild.

Yes, it’s totally true that even the attacker can inject a small amount of message at the beginning, he’s still unable to read the encrypted data. But let’s see how Kurmus’ attack works. (Of course, this hole has been patched by Twitter)

You can update your Twitter status with its API by posting your new status to http://twitter.com/statuses/update.xml, as well as your user name and password. The message is something like below:

POST /statuses/update.xml HTTP/1.1
Authorization: Basic username:password
User-Agent: curl/7.19.5
Host: twitter.com
Content-Length: 22
Content-Type: application/x-www-form-urlencoded
status=your new status

All that the attacker need to do is to inject a POST request header, and post the victim’s POST request to his own twitter account:

POST /statuses/update.xml HTTP/1.1
Authorization: Basic username:password
User-Agent: curl/7.19.5
Host: twitter.com
Content-Length: 140
Content-Type: application/x-www-form-urlencoded
status=POST /statuses/update.xml HTTP/1.1
Authorization: Basic username:password

Obviously, the server would be fooled to post the victim’s credential, and now, the attacker gets the user name and password of the victim.