Best Practices for using onResume() in Android Apps

onResume() is a tricky part of an Android’s application life cycle that is called after onRestoreInstanceState(bundle), onRestart(), or onPause(). Its’ typical usage looks like this inside an Activity:

@Override
protected void onResume() {
	super.onResume();
	//do something
}

There are two things to be aware of when using onResume():

1)      The application may not be visible yet to the user

2)      Code that you want to access may not be fully initialized yet.

It seems very simple on the surface. When an application resumes it’s really no different than when you wake up in the morning. It may take some time to get going and there may be certain necessary rituals to be completed. For example, some people need a few cups of coffee (or tea), and applications are the same way. Of course, applications don’t drink coffee or tea (yet). But, anyway, it takes time and there may be certain rituals that need to be done for certain aspects of your application to spin back up. This is especially true when you have implemented your own threads.

It’s important to note: onResume() does not indicate that the application knows anything about the state of your application, and this is where you can get into trouble. This event is, for the most part, just an announcement by the operating system that it has resumed your Activity and that you can start accessing your app or hardware items such as the camera.  What makes this confusing is that some aspects of your Activity will come back to life without your help. Examples of this include user interface components. And, other aspects of your app will not automatically come back to life. An example of this is if you built any custom threads.

So, some key items to consider in your code are:

1)      If you are concerned about visibility then check onWindowFocusChanged(). You can do this using the pattern described below for #3 and #4.

2)      Did you pause any threads prior to the onResume() event? If you did, you’ll need to unpause them. If you don’t unpause them they won’t start back up again automatically.

3)      Do you have anything that takes additional time to re-initialize? An example of this might an RSS refresh request is kicked off, but the response payload hasn’t been received and processed yet and you want to synchronize that with other methods.

4)      If the device is under load when your application resumes, the methods you attempt to access and their responses, as well as any event handling, may be sluggish. Examples of a device under load include limited memory conditions, and/or high CPU usage, and/or high-bandwidth usage. If you don’t handle this properly the app will crash.

To work around items #3 and #4, there are several relatively easy ways to help prevent your app from crashing: Handlers and AsyncTasks. Use Handlers or AsyncTask for managing aspects of your application that don’t or can’t spring immediately back to life. If you aren’t familiar with Handlers or AsyncTask, they give you an easy way to off-load time-consuming or intensive tasks from the main user interface thread, and they also provide easy methods for re-synching messages, methods or objects back into the main thread. The concept behind this is the end user can continue working with a compliant user interface that still accepts input, while these special methods work on their tasks in the background, and then return control back to the main thread when the tasks are done.

There are plenty of posts that explain Handlers and AsyncTasks and show how to fully implement them, so I’m not going to cover that. I will, however, show you one example to demonstrate what I’d consider a best practice to cover you on items #3 and #4. In this example, and in the context of the application being resumed, it must now wait until the RSS feed has been retrieved before running an analysis on the feed. Both the RSS HTTP request/response and the analysis can be time consuming, and the analysis could still be running in the background while another RSS feed request is taking place. By using background threads, we can better manage this scenario and reduce the chance of an application crash.

public boolean getRSSPayloadReady(){
	boolean rssRecieved;
	//determine if RSS has been recieved and processed.
	....
	return rssRecieved;
}

@Override
protected void onResume() {
	super.onResume();
	rssQueue.unpause(); //threaded method for retrieving RSS
	delayedStart(15000);
}

/**
* Use with onResume().
* Check for RSS update in the background using a specified second delay.
* @param delay how long to wait in milliseconds
*/
public void delayedStart(final int delay){
	final Handler handler = new Handler();

	Runnable rssTask = new Runnable() {

		@Override
		public void run() {

			try{
				handler.postDelayed(new Runnable() {

					@Override
					public void run() {

						try{
							boolean test = getRSSPayloadReady(); //Has RSS refresh completed?

							if(test == true){
								//this algorythm runs as AsynTask
								runParsingAlgorythm(); //won't work if RSS payload = null
							}
							else{
								sendToastMessageRSSFailed(); //Let user know there was a problem.
							}
						}
						catch(Exception exc){
							Log.d("Test","delayedStart(): " + exc.getMessage());
						}
					}
				}, delay);
			}
			catch(Exception exc){
				Log.d("Test","delayedStart(): " + exc.getMessage());
			}
		}
	};

	Thread rssThread = new Thread(rssTask);
	rssThread.start();
}

Reference:

Android Activity and Application Life Cycle

7 required improvements for the Web, HTML and JavaScript

Here’s my 2012 web developer wish list for improvements that I’d like to see happen in the web developer world. If HTML and JavaScript want to be considered enterprise ready for commercial-grade deployments then here’s some things that are needed today.

For clarity, I consider a commercial software deployment to be one that contains over one thousand lines of code, at least two custom .js libraries and involves at least two developers and some sort of code versioning system.

  1. Refactoring. Not having this capability continues to be a huge productivity issue for large projects. Try refactoring across six JavaScript libraries and 1200 lines of code using Notepad++.
  2. Even stronger scope enforcement in JavaScript classes. One wrong misspelling and you can spend fun filled hours (or days) tracking down a private variable that turned itself into a global variable.
  3. Built-in support for code comments. Visual Studio does a fine job, for example. But, it’s still kind of a hack to make it work. I’d like the built-in ability to create comments for methods and classes directly and then be able to access those comments via intellisense throughout any file in the project. Again, this is all about productivity by having this information accessible at your fingertips.
  4. Better built-in JavaScript checking for IDEs. I’d like to see built-in JSLint-like capabilities that have been updated to the latest HTML, JavaScript and CSS3 versions, and not some third party plug-in that’s optional.
  5. Best practice whitepapers. These would be whitepapers written by the browser vendors that provide guidelines on the correct patterns to use when building apps against their browsers. Seriously, it’s been roughly 21 years since we started using browsers and there’s no guidance at all from the powers that be.  Honestly, I’m stunned that these don’t exist. That would be similar to Microsoft publishing .NET and then not providing any conceptual help documentation.
  6. Official tools for browser certification and testing. The folks that build the browsers don’t give us a way to verify if we are building our apps in the best way possible. If these items existed, then quality could get a lot better, and we’d all learn a lot too.
  7. Slower browser release cycles. A slower release cycle for browsers and more improved security and stability. I already blogged about this here.

New Developers – don’t use shorthand code!

Our team is increasingly working with folks who don’t have a developer background. So, I’ve been spending time providing tips-and-tricks on some of the basics they’ll need to help them over their first few speeds bumps.

The first thing I always stress is learning how to debug. It’s imperative to know how to do it well, and if you don’t know how to do it then you’ll hate programming forever. It’s just like swimming. If your first experience is bad you may never jump back in the water again. But if you learn to do it right the first time, you are more likely to try it again and again. And, you may even find yourself having fun with it.

One of the fundamentals of debugging is writing verbose code. Those of us who have been doing it a while tend to cut corners sometimes, and we write things in shorthand like this:        

 if(something == 0) return false;

The problem with this line of code is very hard to debug. The recommended best practice is to write the code as such:        

if(something == 0)
{
     return false;
}

This enables three things to happen. First, you can set the debugger on the “return” line. This means you can check to see if the “if” condition actually occurred or not. Second, if there is ever an error you’ll know exactly which line it occurred on without having to decipher which part of your shorthand code caused the problem. This will save you time and headaches. And lastly, it’s much easier to read, especially when your programs start to get large.

So, my recommendation is to “spell it out”!