Android through the eyes of iOS: The app lifecycle and how to make things happen (Part 3)


If you want to test out some basic code in Xcode/iOS, the first port of call is usually viewDidLoad: in the app's first view controller, since here we can run basic stuff that fires NSLog or load things into the view. So how do we do the same in Android?

Locating the Activity file

If you create a new app in Eclipse (using File>New>Android Application Project) and navigate to the src>com>[YOUR-NAME]>[APPLICATION-NAME] file you will find your main application file, usually named MainActivity.java. In here there is, after the package and import information a piece of code that reads something like this:

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {

// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

}

Taking advantage of lifecycle events

onCreate() is your first opportunity in the app's lifecycle to run some code, e.g. to print a message in the log, but there are a range of other methods also available, which can be added to this MainActivity code and I list them below on the left with the iOS equivalents (from the UIApplication Delegate Protocol) on the right:

onCreate()application:didFinishLaunchingWithOptions:
onStart()applicationDidBecomeActive:
onResume()applicationWillEnterForeground:
applicationDidBecomeActive:
onPause() / onStop()applicationWillResignActive:
applicationDidEnterBackground:
onDestroy()applicationWillTerminate:

Note: The table shows rough equivalents and sometimes iOS breaks down a single Android state into two unique events (or merges events like pause and stop).

Comparison to Xcode

While you could use the application delegate (or AppDelegate) to fire log messages and so forth in Xcode, it is unlikely that you would do this a great deal, because on the creation of an iOS app project you normally create a view controller at the same time and it is here in the viewDidLoad:, viewWillAppear:, etc. methods that you most commonly experiment with code.

Further Reading

Activity Lifecycle (Android, Developer site)

Starting an Activity / Understanding the Lifecycle Callbacks (Android, Developer site)

The accepted reply to this StackOverflow post demonstrates how to take advantage of the Android methods listed in the table above.

App States and Multitasking (Apple, Developer Site)

Android through the eyes of iOS: Classes and Methods (Part 1) | Android through the eyes of iOS: Object classes and class extension (Part 2)


Endorse on Coderwall

Comments

Post a Comment