Skip to main content

Posts

Showing posts from September, 2013

Android Looper and Toast from WorkerThread

Have you ever tried to launch Android Toast message from worker thread? Probably you are wondering why the heck it is giving this error- java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare() In this article we are going to explore reason behind the above exception and try to understand how Looper works in Android. At the end, I am going to explain one approach to run Toast from a worker thread, but before that we need to understand how Looper works. If you already know in/out of Looper, you can skip below section and directly move to the solution part. Looper is a very basic wrapper class which attach a MessageQueue to a Thread and manage this queue. MessageQueue is a structure to sequentialize simultaneous processing requests of a Thread.  In Android, message/request processing classes like Handler uses Looper to manage their respective MessageQueue. Looper = Thread + MessageQueue Android Looper Life Cycle: As you can see in the abo

Java Reflection as Android API

Have you ever tried or wished to re-use or access source code which is part of a different Android APK ? If "Yes", then this article is for you. Well, I must agree its not a very common use case and when it comes to API in Android, we rather prefer JAR or Remote Service to expose functionalists. Java Reflection can be an alternate and useful API approach to expose functionalists from an APK or Application. Here I'm going to explain a design approach where we can define API for Android using Java Reflection. For this example, Host.apk is an Application which hosts one API method which we are going to access from another application Client.apk . Host.apk includes- HostApi.java which defines API method getMeta() . This method returns some pre-defined Text appended to calling Application's Package name. package com.pras.host; import android.content.Context; public class HostApi {      Context mContext;      public HostApi(Context context) {          this.mContext = co