Shipping your Android SDK anytime on live devices


If your product depends upon a mobile SDK, then you must be knowing the real pain of shipping the latest version of your SDK onto the live devices through host apps. There is a way to tackle this issue with an interesting approach.

We are going to use dynamic class loading using classloaders provided by Android system.

Class loader

The Java classloader is a part of the Java Runtime Environment that dynamically loads Java classes into the Java Virtual Machine. Usually, classes are only loaded on demand. The Java runtime system does not need to know about files and file systems because of classloaders.[2]

We are gonna use a special class loader from Android system called PathClassLoader, which provides a simple ClassLoader implementation that operates on a list of files and directories in the local file system, but does not attempt to load classes from the network. Android uses this class for its system class loader and for its application class loader(s).

Chaining the ClassLoaders

[3]

So we can create a hierarchy of classloaders that can share the definition of the classes without any duplication. So in this case, classloader A has already loaded class A, so loaderB.loadClass('A') will delegate the request to loaderA instead of reloading it. This feature comes handy for our purpose.

Application lifecycle on Android OS

[4]

When a user clicks on the app icon, a new application thread is started which contains a new instance of the dalvik vm. This dalvik vm has a classloader that loads the dex file (APK file) and kicks off the lifecycle of the app.

What if we provide one more dex to load at runtime?

Consider the AAR file that we ship, contains one more DEX file which is loaded by the AAR at the time of initialization. This will allow us to change the functionality without having to force update the AAR on the devices.

Structure of the project

app : Host app where you will integrate the SDK

dependencies {
  ...
  compile project(":lib")
  ...
}

lib : Our static SDK code that ships with the app. This has the secret sauce of loading the functionality runtime.

dynamiclib : SDK that does the implementation of the dynamic functionality of the SDK.

Let’s divide our tasks and decode one by one.

Code architecture

To bring in the dynamic features, I am going with an interface approach. So our dynamic lib and lib will share one common interface.

    public interface IMethods {
        String getVersion();
        void log(String message);
    }

Make sure that the package name for this interface will be the exactly same in both lib and dynamiclib module.

This IMethods is implemented by a class called MethodsImpl in dynamic lib.

public class MethodsImpl implements IMethods {
  private static final String TAG = "##MethodsImpl##";

  @Override public String getVersion() {
    return "0.1.1";
  }

  @Override public void log(String message) {
    Log.d(TAG, message);
  }
}

Now build this dynamiclib to an APK (as we need a dex file), and host it. I use SimpleHttpServer.

python -m SimpleHTTPServer 8000

This makes dynamic lib available on a link.

Let’s build the last leg of the solution, downloading the APK and loading the classes using a PathClassLoader.

Downloading the APK

Use any way to download the APK, I have used an AsyncTask

Store the downloaded APK on internal storage sandboxed for our package

context.getFilesDir() gives the path to the internal sandboxed storage for the package. Store the downloaded APK in this folder.

Load the downloaded APK and cast it to the IMethods
// INTERNAL_DEX_PATH = context.getFilesDir() + FILE_NAME this is path to the file we have downloaded
private static void loadSdk(Context context) {    
    PathClassLoader pathClassLoader =
        new PathClassLoader(INTERNAL_DEX_PATH, context.getClassLoader());
    try {
      Log.d(TAG, "loading sdk class");
      // This step load the implementation of IMethods dynamically
      Class sdkClass = pathClassLoader.loadClass("net.media.dynamiclib.MethodsImpl");
      // This step creates the new instance of MethodsImpl and casts it to IMethods
      IMethods methods = (IMethods) sdkClass.newInstance();
      // This should log this message on logcat
      methods.log("testing this");
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

Logs when you run the app is

12-22 17:16:29.036 10926-10926/net.media.injector D/## Injector ##: load()
12-22 17:16:29.131 10926-10926/net.media.injector W/gralloc_ranchu: Gralloc pipe failed
                                                                    
                                                                    [ 12-22 17:16:29.132 10926:10926 D/         ]
                                                                    HostConnection::get() New Host Connection established 0xad9f6d80, tid 10926
12-22 17:16:29.174 10926-10954/net.media.injector D/NetworkSecurityConfig: No Network Security Config specified, using platform default
12-22 17:16:29.222 10926-10954/net.media.injector D/## Injector ##: File output stream is => /data/user/0/net.media.injector/files/lib.apk
12-22 17:16:29.523 10926-10953/net.media.injector I/OpenGLRenderer: Initialized EGL, version 1.4
12-22 17:16:29.526 10926-10953/net.media.injector D/OpenGLRenderer: Swap behavior 1
12-22 17:16:30.064 10926-10926/net.media.injector D/## Injector ##: downloaded
12-22 17:16:30.064 10926-10926/net.media.injector D/## Injector ##: /data/user/0/net.media.injector/files/impl.dex
12-22 17:16:30.064 10926-10926/net.media.injector D/## Injector ##: /data/user/0/net.media.injector/files/impl.aar
12-22 17:16:30.065 10926-10926/net.media.injector D/## Injector ##: /data/user/0/net.media.injector/files/lib.apk
12-22 17:16:30.170 10926-10926/net.media.injector D/## Injector ##: loading sdk class
12-22 17:16:30.171 10926-10926/net.media.injector D/##MethodsImpl##: testing this

This approach will allow you to update the functionality with a strong interface defined between shipped code and dynamic part of the SDK. This is the case where host app keeps interacting with your SDK using a set of functions. If your SDK is, initialize once and forget, then you can keep entire logic in dynamic part of the SDK.

Security

Security is going to be one of the biggest concern in this approach. There are some standard ways to validate the dex file like using MD5 hashes. Once you securely download the DEX file in the internal storage then other concerns are as same as they are for shipped SDK.

Github repo for the source code.

Get in touch with me if you need any help or you find something wrong with this post. Happy coding :).



References

[1] Android system fundamentals

[2] ClassLoaders Wiki

[3] [How do classloaders work]((https://myprogressivelearning.wordpress.com/2014/10/28/class-loading-in-java-java-classloader-what-and-how/)

[4] Android Application lifecycle

How to use packages specifically for Debug/Release builds in Android


Preface

Currently I am working on an Android app for one of the most interesting startups in Fintech. I have been really choosy about the packages that are getting shipped with this app, simply because it involves a lot of money related functionalties. During the development, I came across a requirement that debug builds should have instabug integrated for reporting UI issues easily. APK size matters a lot, so I wanted to achieve this without shipping Instabug SDK in production builds.

How to do this?

Gradle file

...
dependencies {
    ...
    compile appDependencies.rateUs
    compile appDependencies.markdownJ
    debugCompile(appDependencies.instabug) {
        exclude group: 'com.mcxiaoke.volley'
    }
}
...    

I changed the way gradle compiles instabug dependency. Now it’s done during debug builds only. Release builds will not consider this dependency.

How to use this conditional dependency in code?

Create debug and release folders inside the src folder of your app. Create the exact same package structure (same as main folder) in both of these folders. Create a class with overriding nature i.e. same name and methods. Now write add instabug initialization inside the debug flavour, while release flavour won’t have this bit. Update your main Application class to include the initialization of this newly created class.

Application class in main.

    @Override
    public void onCreate() {
        super.onCreate();        
        ...
        SimplAppInitializer.init(this);
        ...
    }

And you are done, now the instabug will be only compiled with the debug builds and not with your production builds.

Let me know if there are some issues/suggestions related to this post. Happy coding \m/

Docker + Golang web apps using Godep on AWS with Elastic Beanstalk using CodeShip


A lot of things in one title right :D. We are coming up with a small tool for developers that is going to help them to distribute mobile application releases easily, and mainly during development phase. Initially we were using the free dyno provided by Heroku, as staging environment. But as the date of release is approaching, it was time to move onto more scalable (heroku is scalable but becomes a bit costly when you start using it for production purpose) and cheaper infrastructure.

Golang web application structure

My web application is based on slightly customised version of Gin + PostgreSQL at the backend, AngularJS + Bootstrap 3 + Custom CSS for front end. I have been using Godep for dependency management on Heroku. And I feel, this is one of the better ways than creating a bash script with all the go get. If any of the dependencies have introduced some changes that breaks the existing apps, then you are kind of fucked. Godep basically works on the commit id of the code that you have checked out while development.

Note 1: Also a lot of people on the forums suggested me to go for precompiled binary to reduce the size of the docker images. I haven’t given a try to it. You have to use a few ready made tools to create binary for your production environment.

Note 2: If you are not sure which ORM you should use,then give a try to Gorm.

First thing first, Install boot2docker

As you will first test everything locally, you will need boot2docker. And just initialise it with following commands

boot2docker init
boot2docker start

Creating a Dockerfile

# Using wheezy from the official golang docker repo
FROM golang:1.4.1-wheezy

# Setting up working directory
WORKDIR /go/src/<project>
Add . /go/src/<project>/

# Get godeps from main repo
RUN go get github.com/tools/godep

# Restore godep dependencies
RUN godep restore

# Install
RUN go install <project>

# Setting up environment variables
ENV ENV dev

# My web app is running on port 8080 so exposed that port for the world
EXPOSE 8080
EXPOSE
ENTRYPOINT ["/go/bin/<project>"]

Most of the things in this Dockerfile are self explanatory (List of commands).

Golang team is kind enough to create the debian images with the latest Golang versions available. So the first line means that I intend to run this in a container with OS Debian(wheezy) with Golang 1.4.1.

What about the DB connection ?

So in my DEV environment I had a postgres instance running locally. I struggled a bit for allowing my docker container to connect the database on the host but it was taking a lot of time. So for a quick fix, I created a new app on heroku, added a free postgres addon.

Building the repository

So we have a Dockerfile, now the next step is to build the repository for the container and running it. Your working directory is the root of your project.

docker build -t <project_name> .

You will see all of the commands that we have added in the Docker file will start executing one by one. At the end if everything goes well you shall see Successfully built <ID>

If you see this message then we are all set to deploy project on the cloud. For testing you can publish the repository with following command and test it from local browser

docker run --publish 3000:8080 --name <tag-name> --rm <project-name>

Check your docker container ip address using following command

boot2docker ip

And now go to your browser and enter address as http://ip_address:3000 and everything should work.

Setting up continous integration

I went through a couple of CI tools supporting Golang web apps and settled down onto Codeship. (I am evaluating Shippable).

For my Go projects, I don’t keep up with the regular naming conventions i.e. github.com/rainingclouds/project_name. So I had to work a bit on the test scripts as Codeship assumes you are following the naming conventions. (The reason I don’t follow it because, the project is not supposed to be reused as it is by anyone else :))

mv ../distribute ${HOME}/src/distribute
cd ${HOME}/src/distribute
go get github.com/tools/godep
godep restore
go get

And then you can put your testing commands. I am not using any framework for writing tests. Default testing package is more than enough for me at this stage.

go test <module_to_test> -v

Setting up the deployment hook

Codeship comes up with Elastic beanstalk deployment hook. For that you have to configure a few things before you can use it.

Configuring ElasticBeanstalk environment

Create IAM user for codeship

I keep on using different users for these different services, So that we can manage the access independently. I created a user with all access for Elastic Beanstalk. There is a ready template for this in AWS IAM panel.

Create a new application

Create a new application in elastic beanstalk and don’t select a demo application option. You will see a Create Application button on right top of the panel. For this you will have to upload a zip of your source code manually.

Note : I am also using ELB in front of my EC2 instances. For https, I am doing the SSL termination at LB level, and then redirecting it to my Golang application.

Create a new environment

Create a new environment inside your new application.

Configure codeship deployment hook

Once you have configured AWS, go to codeship and put all the information in AWS Beanstalk deployment settings page.

Done

If all goes well then the entire pipeline is ready. For testing make a small change and push it to your configured branch. You will see that the new task in the codeship with the exact status of it :).

map to struct in Golang


Recently I was working with a piece of code where I had to convert a JSON into a Golang struct. I faced hell lot of issues, and waster a bit of time in achieving that, so thought of documenting it.

Scenario

I have a struct called User, which has fields. There were no issues with primary data types, but when it came to time.Time, it started fucking me.

  Id      int    `json:"user_id"`
  AuthKey string `json:"-" sql:"not null;unique"`
  
  Name         string `json:"user_name" sql:"not null;unique"`
  EmailAddress string `json:"email_address" sql:"not null;unique"`
  Password     string `json:"-" sql:"not null"`

  AccountId int `json:"account_id" sql:"not null;unique"`

  CreatedAt time.Time `json:"created_at"`
  UpdatedAt time.Time `json:"updated_at"`
  DeletedAt time.Time `json:"deleted_at"`

A bit of googling landed me onto http://github.com/ottemo/mapstructure. This had everything I wanted. (Prefer https://github.com/mitchellh/mapstructure repo over as ottemo/mapstructure has an AdvancedDecodeHook that helps a bit in this situation)

Solution

Suppose that body has the entire JSON. It has some fields along with User struct with user as key.

  • First we will convert the JSON into a map[string]interface{}
  var data map[string]interface{}
  err = json.Unmarshal(body, &data)
  if err != nil {
    return nil, err
  }
  • Okay so data contains our JSON, now as we have a custom fields time.Time we will have to write our own decoder, which means create on AdvancedDecodeHook func and pass it to the DecoderConfig
func myDecoder(val *reflect.Value, data interface{}) (interface{}, error) {
  if val.Type().String() == "time.Time" {    
    value, err := time.Parse(time.RFC3339Nano, data.(string))
    val.Set(reflect.ValueOf(value))
    return nil, err
  }
  return data, nil
} 

So lets understand the structure of this hook - You get two parameters:

  • val => indicates type of the data
  • data => value of that data

This function returns an interface and an error. Now this AdvancedDecodeHook works in a way that if you return nil in place of interface, it the decoder assumes that our custom decoder has parsed the value for the given data, and it leaves it in that way. In case of error the entire parsing fails. So you have to decide on whether to throw the error or set a default value when parsing fails.

  • And now just write a function to return the decoder with our custom configuration
func getDecoder(result interface{}) (*mapstructure.Decoder, error) {
  return mapstructure.NewDecoder(&mapstructure.DecoderConfig{
    AdvancedDecodeHook: myDecoder,
    TagName:            "json",
    Result:             result,
    WeaklyTypedInput:   false})
}

The parameter that we pass in is the result type we expect. This has to be the pointer to the struct.

  • And finally call it from your routine
  decoder, err := getDecoder(&user)
  if err != nil {
    return nil, err
  }
  err = decoder.Decode(data["user"])
  if err != nil {
    return nil, err
  }
  • And you are done.

Final code

So the final code looks like this

func myDecoder(val *reflect.Value, data interface{}) (interface{}, error) {
  if val.Type().String() == "time.Time" {    
    value, err := time.Parse(time.RFC3339Nano, data.(string))
    val.Set(reflect.ValueOf(value))
    return nil, err
  }
  return data, nil
} 

func getDecoder(result interface{}) (*mapstructure.Decoder, error) {
  return mapstructure.NewDecoder(&mapstructure.DecoderConfig{
    AdvancedDecodeHook: myDecoder,
    TagName:            "json",
    Result:             result,
    WeaklyTypedInput:   false})
}

func GetUserFromJSON(jsonUser string) (*User,error){
  var data map[string]interface{}
  err = json.Unmarshal(jsonUser, &data)
  if err != nil {
    return nil, err
  }
  decoder, err := getDecoder(&user)
  if err != nil {
    return nil, err
  }
  err = decoder.Decode(data["user"])
  if err != nil {
    return nil, err
  }
  return &user,nil
}

Thank you guys, keep coding :)

Writing Android app with Kotlin


When I read the description about kotlin, I thought of it as a very beautiful port of Java (as its a JVM based language and 100% interoperable with Java). I have been trying to like Scala for a lot time now, but hell lot of options for everything, complex semantics makes the code unreadable and confusing (for me). But kotlin, according to me is a decisive approach towards making Java more functional and more compact for developers.

The first thing I searched when I read about Kotlin was, about Android support. Scaloid being more and more popular and I being completely not in love with Scala, this was going to be an interesting thing for me. Kotlin does have support for Android and they do have amazing documentation about both language as well as Android support, So I went ahead and tried one simple list app with an adapter and a fragment, just to simulate a simple part of general Android application.

Setup

  • Install Kotlin plugin available in Preferences for Android Studio.
  • Add following classpath to the gradle script
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:0.9.206"
  • And add the dependency in the application gradle script
compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"

The Application

I started with writing a HackerNews listing app. But then restricted it to simulating the API call with a stub so as to focus onto the Kotlin more than the actual functionality of the application.

Code

Let’s dive into some code.

Home

It’s the main activity (launcher) of the application.

open class Home(): ActionBarActivity(){

    val logTag = "###Home###"

    override fun onCreate(savedInstanceState: android.os.Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_home)
        val transaction = getSupportFragmentManager().beginTransaction()
        transaction.replace(R.id.posts_container, PostListFragment.Maker.Create())
        transaction.commit()
    }
}

Things I loved

  • Kotlin has val, var keywords to separate out the final and variables (if we compare it with Java). I personally feel that val and var are the best ways to indicate that if a member is final or not.
  • Nullable is always appended with a ‘?’. So this is again a very informative way of indicating the possible exceptions that can happen when you are working with a particular member or parameter.

PostListFragment

This is the fragment that contains list of posts. It’s a DialogFragment, so as to make it available to be used as a dialog as well.

open class PostListFragment() : DialogFragment() {
    val logTag = "###PostListFragment###"
    var postList: ListView? = null
    var baseView: View? = null
    var postsAdapter: PostListAdapter? = null
    var handler: Handler? = null

    object Maker {
        fun Create(): PostListFragment {
            return PostListFragment()
        }
    }

    override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        baseView = inflater?.inflate(R.layout.fragment_post_list, container, false)
        postList = baseView?.findViewById(R.id.post_list) as ListView
        postsAdapter = PostListAdapter(getActivity(), postList as AbsListView)
        postList.setAdapter(postsAdapter)
        handler = Handler()
        return baseView
    }

    override fun onResume() {
        super.onResume()
        Post.Maker.GetList {
            Log.d(logTag,"Testing get list =&gt;" + it.get(0).post)
            postsAdapter?.postList?.addAll(it)
            handler?.post {
                this.postsAdapter?.notifyDataSetChanged()
            }
        }
    }
}

Things I loved

  • The biggest advantage Kotlin gives you is passing functions as parameter (Functions are first class citizens). And this helps us to remove all those interfaces we end up creating to circumvent this problem in Java. (Look at the Post.Maker.GetList)
  • In Kotlin, you have to write all the static methods separately inside an object. Most of the times the static methods are factory methods, and this helped me to make the code more readable. So I call each of the object inside the class as Maker, and write different factory method inside it. This is completely possible with Java by writing inner classes, but this being the semantics of the language, forces us to write the factory methods like this.

Things I hated

  • ‘?’ comes really handy to avoid null pointer exceptions. But I feel that also is a problematic. In most of the cases during development, null pointer exceptions help us to fix issues quickly. Now as this was a small skit, I never faced any null pointer exception but while writing some complex code this could make a few things really tricky.

Post
This is the model class containing info related with each post.

data class Post(val id: Long, val post: String, val by: String, val postedAt: Date) {
    object Maker {
        fun GetList(onSuccess: (posts: List) -&gt; Unit) {
            val posts = ArrayList()
            for (a in 1..10) {
                posts.add(Post(a.toLong(), "Test", "Akshay", Date()))
            }
            onSuccess(posts)
        }
    }
}

Things I loved

  • Making class as a data class makes it easy to debug. Using instance of this class in logs prints the values of each of the field of the class in readable format. I feel this is one of the best thing. This can be done in Java by overriding toString() method.
  • The way you define members of the class, is much much compact and better. Now my model classes will just have the Maker which will have the factory methods.
  • Functions are first class citizens! Look at the way GetList is coded. It accepts a function, that takes up List of Post as param and returns nothing. (Unit in Kotlin means nothing). So forget all the interfaces we used to write for circumventing the problem of passing functions as arguments.

PostListAdapter

This is the list adapter for post list view.

open class PostListAdapter(val context:Context,val listView: AbsListView): BaseAdapter(){

  private val logTag: String = "###PostListAdapter###"
  var postList = ArrayList()

  override fun getCount(): Int {
      return postList.size
  }

  override fun getItem(position: Int): Any? {
      if(position &gt;= postList.size)
          return null
      return postList.get(position)
  }

  override fun getItemId(p0: Int): Long {
      if(p0 &gt;= postList.size)
          return -1
      return postList.get(p0).id
  }

  override fun getView(position: Int, view: View?, parent: ViewGroup): View? {
      var cachedItem: ItemCache?
      var contentView: View ? = view
      when (contentView) {
          null -&gt; {
              contentView = LayoutInflater.from(context).inflate(R.layout.layout_post_item, parent, false)
              cachedItem = ItemCache(textView = contentView?.findViewById(R.id.post) as TextView)
              contentView?.setTag(cachedItem)
          }
          else -&gt; {
              cachedItem = contentView?.getTag() as ItemCache
          }
      }
      val currentPost = getItem(position) as Post
      cachedItem?.textView?.setText(currentPost.post)
      return contentView
  }

  class ItemCache(val textView: TextView?)
}

This all works well. The source code is available at https://github.com/akshaydeo/kotlin_android.

Some analysis of APK

  • The very very important thing to look at is, the number of classes inside your APK. Don’t worry, its gonna be huge that the APK you will create with same functionality using JAVA. For example the application that I have created contains 3561 classes. (I am planning to write the same app using Java and compare the results with Kotlin app). So running proguard during the debug builds is very essential in this case.
  • Also I faced gradle crashing problem because of the default VM params. So you will have to change them using preferences. I changed them to
-XX:MaxPermSize=1024m -XX:MaxHeapSize=256m -Xmx256m

Important Links for Kotlin

I will be updating this post as I progress in analysing the side effects of using Kotlin for Android development.