2011-02-24

Android's Main Thread

Android's main thread is the the most important thread for your Android app. Not only the UI stuff is done on the main thread but also your services and much more is running on the main thread.

It's really important not to block the main thread longer than it's absolutely needed. It's always a good idea to not access the network and the filesystem on the main thread. Because of that the nice guys at Google brought us the StrictMode in Android 2.3 to see if your app does IO on the main thread.

But it's also a bad idea to do anything else that is time consuming on the main thread e.g. when handling the onClick of a button or something similar. You can easily spot those long running tasks on the main thread by using the following code. You should run it as early as possible in your application (Application#onCreate is a good place) and you should consider removing it from release builds:


 Looper.getMainLooper().setMessageLogging(new Printer() {
                long time = -1;
                String info = null;
               
                @Override
                public void println(String line) {
                    if(line.startsWith(">>>")) {
                        time = System.currentTimeMillis();
                        info = line;
                    } else {
                        long now = System.currentTimeMillis();
                        if(now-time>500) {
                            Log.d(TAG,"!!!!!!!!!!!! Too slow:"+info);
                        }
                    }
                   
                }
               
            });

With this code you will see a log entry every time you are doing anything on the main thread that takes more than 500 miliseconds. One nice thing about this approach is that it doesn't need one of the newer Android versions (all it uses is API Level 1!).

No comments:

Post a Comment