Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Developing Mobile Applications Week 2 Activity Lifecycle Steve Jones Department of Computer Science University of Waikato [email protected] Activity Lifecycle 1 Today Android application components Understanding the activity lifecycle Coping with orientation changes Adding an Action Bar to PropertyFinder Activity Lifecycle 2 Application/project components Creating an Android Application project produced all Java source code goes here you organise it into sensible packages the Java file was created for us and contains a trivial Activity class Activity Lifecycle 3 Application/project components Creating an Android Application project produced the Java library for the version of Android that we are compiling against automatically added to project and Java build path Activity Lifecycle 4 Application/project components Creating an Android Application project produced defines characteristics of the application Activity Lifecycle 5 Application/project components Creating an Android Application project produced Java classes automatically generated by the build process treat as READ ONLY files are automatically added when an executable is built the installer (.apk) file will appear here treat as READ ONLY proguard deals with things relevant to a public release (shrinking, obfuscating, optimising) project properties are things like target API level treat both as READ ONLY Activity Lifecycle 6 Application/project components Creating an Android Application project produced things you need to bundle with the app but aren’t standard Android resources (eg you might want to bundle a pre-constructed database) Activity Lifecycle 7 Application/project components Creating an Android Application project produced additional Java libraries required by the application Activity Lifecycle 8 Application/project components Creating an Android Application project produced definitions for layouts, constant values (eg UI strings), icons, images, menu content etc Activity Lifecycle 9 Application/project components Creating an Android Application project produced application icons for different screen densities definition of the UI layout definition of application’s menu content definition of string constants used in the app and UI styles/themes used by the app some styles/themes are Android version dependent : v11/v14 used when device supports them Activity Lifecycle 10 Application/project components Building an executable creates (in the ‘bin’ folder) standard class files produced by the Java compiler Activity Lifecycle 11 Application/project components Building an executable creates (in the ‘bin’ folder) ‘dexed’ versions of the Java class files Android uses its own virtual machine called Dalvik Java byte code is converted to Dalvik byte code (a dalvik executable) Android Java class libraries are actually a subset of Apache Harmony (open source Java runtime) Activity Lifecycle 12 Application/project components Building an executable creates (in the ‘bin’ folder) ‘dexed’ versions of additional Java libraries (none here) Activity Lifecycle 13 Application/project components Building an executable creates (in the ‘bin’ folder) the application package file that is loaded on to a device for installation Activity Lifecycle 14 Application/project components Building an executable creates (in the ‘bin’ folder) a zip archive of the application’s resources Activity Lifecycle 15 Application/project components The .apk file is just a zip archive containing the files needed for installation on device • APK installer on device unzips and places files into appropriate locations the real executable Activity Lifecycle 16 Application/project components During development we are mainly concerned with • making sure AndroidManifest.xml correctly describes the application • adding Java code to the ‘src’ folder • adding resources (icons, images, layout defns, menus, constants etc) to the ‘res’ folder Activity Lifecycle 17 AndroidManifest.xml An app needs a special file AndroidManifest.xml that describes its requirements, capabilities and components <uses-xxx> uses-feature entries describe the features that a device should have for the app to work (eg a camcorder app needs a device to have a camera) uses-permission entries describe the privileges that the app wants to be granted (eg network access, read/write SD card, initiate phone calls, use location sensors). Users need to agree during installation uses-sdk entry states the minimum Android version that is required for the app to work (eg it uses a widget that was introduced in Android 4 so won't work on 1.x-3.x devices) The Play Store can filter available apps by comparing these characteristics to the user's device Activity Lifecycle 18 AndroidManifest.xml An app needs a special file AndroidManifest.xml that describes its requirements, capabilities and components <application> • configures attributes of the application eg • icon, label, UI theme • defines the components that the application consists of eg • activities, services, data providers • defines entry points into the application (one or more activities) Activity Lifecycle 19 PropertyFinder1 AndroidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" the min/max version that you know package="org.stevej.android.propertyfinder1" you app works correctly on android:versionCode="1" android:versionName="1.0" > whether the application’s data can be <uses-sdk backed up using the Android backup android:minSdkVersion="8" infrastructure android:targetSdkVersion="16" /> refer to definitions in resource files <application android:allowBackup="true" android:icon="@drawable/ic_launcher" the application consists of this one android:label="@string/app_name" activity android:theme="@style/AppTheme" > <activity android:name="org.stevej.android.propertyfinder1.PropertyFinderActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> this is the main activity of the </activity> application and can be accessed by </application> launching the app from the home screen/app list </manifest> Activity Lifecycle 20 Activities An activity is the equivalent of a screen/window in a conventional GUI, and an application includes one or more of them An SMS app could have activities for viewing a message list, showing a conversation, creating a message etc Important differences • only one activity visible at a time • you need to be aware of the stack of activities • the system may kill activities that aren't visible • you can allow other applications to launch your application's activities • your application can launch activities belonging to other applications So the SMS app could launch the 'Add contact' activity of the Contacts app, and the Contacts app could launch the 'Create message' activity of the SMS app Activity Lifecycle 21 Intents An intent is a message that is published to activate application components (activities), and contains a bundle of information needed for the activation So an SMS app could publish an intent containing • the identifier of the 'Create contact' activity of the Contacts app • the phone number of the contact and the system handles the activation of the target activity It can be cleverer than that… publish an intent containing • a generic identifier for a 'Create contact' action (no specific app/activity) • the phone number of the contact and the system handles the activation of an activity that can carry out the action (providing the user with a choice if there's more than one – there may be multiple contact manager apps on the device) Activity Lifecycle 22 Activity lifecycle Only 1 activity from 1 application is visible to the user Your application’s current activity can be interrupted, killed, recreated, restarted, resumed by the system Activities need to cope with these changes in state Activity Lifecycle 23 PropertyFinderActivity.java A basic activity all of your activities will extend android.app.Activity package org.stevej.android.propertyfinder1; import android.app.Activity; import android.os.Bundle; import android.view.Menu; called automatically when the activity is created (in this case, the application public class PropertyFinderActivity extends Activity { is launched) @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); set the activity’s UI content to be setContentView(R.layout.activity_property_finder); that defined in res/layout/ } activity_property_finder.xml @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.activity_property_finder, menu); called automatically if a menu has been defined return true; menu layout is created from } /res/menu/activity_property_finder.xml defn and added to the application menu (handle to it } provided by menu) 24 Activity Lifecycle Activity lifecycle You can override all lifecycle methods in your Java code (eg add this to PropertyFinderActivity.java) @Override protected void onPause() { super.onPause(); Log.d("PropertyFinderActivity", "onPause"); } to add behaviour for that point in the lifecycle Activity Lifecycle 25 Restoring state Our activity current has a text label <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".PropertyFinderActivity" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_centerVertical="true" android:text="@string/hello_world" /> </RelativeLayout> What if we add an editable text box? Activity Lifecycle 26 Restoring state Our activity currently has a text label. What if we add an editable text box? <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".PropertyFinderActivity" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_centerVertical="true" android:text="@string/hello_world" /> <EditText android:layout_width=”match_parent" android:layout_height="wrap_content” /> </RelativeLayout> Type in some text, then rotate the device… Activity Lifecycle 27 Restoring state Type in some text, then rotate the device… Ooops! We’ve lost the text! Activity Lifecycle 28 Restoring state Why has the text disappeared? Add logging to onCreate, override onDestroy and add logging Activity Lifecycle @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.d("PropertyFinderActivity", "onCreate"); setContentView(R.layout.activity_property_finder); } @Override protected void onDestroy() { super.onDestroy(); Log.d("PropertyFinderActivity", "onDestroy"); } 29 Restoring state Why has the text disappeared? Orientation changes (amongst many other things) cause the current activity to be destroyed and recreated! We need to store the state of the text box before the activity is destroyed and restore it when the activity is recreated Activity Lifecycle 30 Restoring state Actually most widgets (such as EditText) do this automatically The problem is that the system can only save the state of a widget if it has a unique id Add one <EditText android:id="@+id/text_field" android:layout_width="match_parent" android:layout_height="wrap_content" /> It is good practice to always give UI elements unique ids Activity Lifecycle 31 Restoring state Add this Activity Lifecycle <EditText android:id="@+id/text_field" android:layout_width="match_parent" android:layout_height="wrap_content" /> 32 Restoring state BUT • • • • • what if the user enters text then the phone rings then the user starts up several more apps the system kills your activity to free memory the user returns to your app Text is lost Activity Lifecycle 33 Restoring state savedInstanceState… recall that onCreate has an argument @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.d("PropertyFinderActivity", "onCreate"); setContentView(R.layout.activity_property_finder); } This provides a mechanism by which we can explicitly store/restore activity state We override the activity’s onSaveInstanceState method Activity Lifecycle 34 Restoring state We override the activity’s onSaveInstanceState method finds the UI component with the given ID a key-value map of the data to be saved in the activity’s view hiearchy @Override public void onSaveInstanceState(Bundle outState) { EditText text_field = (EditText) findViewById(R.id.text_field); outState.putString("user_text", text_field.getText().toString()); super.onSaveInstanceState(outState); } add our own data to the map This is automatically called by the system before the activity is destroyed Activity Lifecycle 35 Restoring state And then check if we have saved state in onCreate If so, use it to initialise the text field @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.d("PropertyFinderActivity", "onCreate"); setContentView(R.layout.activity_property_finder); if (savedInstanceState != null) { String user_text = savedInstanceState.getString("user_text"); EditText text_field = (EditText) findViewById(R.id.text_field); text_field.setText(user_text); } } Activity Lifecycle 36 Restoring state You should ensure that the app saves and restores state that is critical to the user seamlessly resuming use of the app This will probably include data that is not automatically saved by a UI widget Activity Lifecycle 37 The Action Bar The application’s menu bar It can support • • • • • navigation within the app displaying of navigation context cues drop down navigation list buttons to access common application functionality inclusion of widgets (such as search box) (Prior to Android 3.0 there was no consistent place to do this, and user needed to explicitly tap the device’s menu button to get the application menu) Activity Lifecycle 38 The Action Bar 4 commonly used segments the app icon view selector action buttons overflow menu if we have multiple screens we can show a < and allow a click to move the user back up the screen hierarchy drop down menu to support navigation to different views within the application the key actions that the user can carry out in the app other, less frequently used actions (eg Settings, About) Activity Lifecycle 39 The Action Bar When we created the PropertyFinder project we got • /res/menu/activity_property_finder.xml <menu xmlns:android="http://schemas.android.com/apk/res/android" > <item android:id="@+id/menu_settings" android:orderInCategory="100" android:showAsAction="never" android:title="@string/menu_settings"/> </menu> • if we had several items we could group them by assigning an android:menuCategory value • and order them within the category • we can make items always appear in the overflow menu ie never as an action button Activity Lifecycle 40 The Action Bar When we created the PropertyFinder project we got • /res/menu/activity_property_finder.xml Activity Lifecycle 41 The Action Bar Add some useful items <menu xmlns:android="http://schemas.android.com/apk/res/android" > <item android:id="@+id/action_search" android:actionViewClass="android.widget.SearchView" android:icon="@android:drawable/ic_menu_search" android:showAsAction="collapseActionView|ifRoom" android:title="@string/action_bar_search"/> <item android:id="@+id/action_map" android:icon="@android:drawable/ic_menu_mapmode" android:showAsAction="ifRoom" android:title="@string/action_bar_map"/> Activity Lifecycle 42 The Action Bar Item attributes <menu xmlns:android="http://schemas.android.com/apk/res/android" > <item android:id="@+id/action_search" android:actionViewClass="android.widget.SearchView" android:icon="@android:drawable/ic_menu_search" android:showAsAction="collapseActionView|ifRoom" android:title="@string/action_bar_search"/> <item this action displays a search widget the system handles its construction and display the icon is built into android search widget collapsed by default, display the search icon if there is room in the action bar (if not it will go in the overflow menu0 android:id="@+id/action_map" android:icon="@android:drawable/ic_menu_mapmode" android:showAsAction="ifRoom" android:title="@string/action_bar_map"/> Activity Lifecycle 43 The Action Bar Add some useful items • the system automatically creates the share menu entries when action for menu item defined as provided by built-in ShareActionProvider <item android:id="@+id/action_share" android:actionProviderClass="android.widget.ShareActionProvider" android:icon="@android:drawable/ic_menu_share" android:showAsAction="ifRoom" android:title="@string/action_bar_share"/> Activity Lifecycle 44 The Action Bar Add some useful items • we can have sub menus <item android:id="@+id/action_sort" android:icon="@android:drawable/ic_menu_sort_by_size" android:showAsAction="ifRoom" android:title="@string/action_bar_sort"> <menu> <item android:id="@+id/action_sort_price_asc" android:icon="@drawable/ic_action_price_asc" android:title="@string/action_bar_sort_price_asc"/> <item there aren’t built in icons for these android:id="@+id/action_sort_price_desc" create them ourselves and add to /res/ android:icon="@drawable/ic_action_price_desc" drawable folders android:title="@string/action_bar_sort_price_desc"/> <item android:id="@+id/action_sort_alpha" android:icon="@android:drawable/ic_menu_sort_alphabetically" android:title="@string/action_bar_sort_alpha"/> </menu> </item> Activity Lifecycle 45 The Action Bar Add some useful items <item android:id="@+id/settings" android:icon="@android:drawable/ic_menu_preferences" android:showAsAction="never" android:title="@string/action_bar_settings"> </item> <item android:id="@+id/action_legal" android:orderInCategory="100" android:showAsAction="never" android:title="@string/action_bar_legal"/> </menu> Activity Lifecycle 46 The Action Bar Some screenshots are with device in portrait orientation, others landscape • in portrait the action bar has been automatically split between the top and bottom of the screen • achieved by setting an application attribute in the manifest <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name” android:uiOptions="splitActionBarWhenNarrow" > Activity Lifecycle 47 The Action Bar What about the app icon and view navigation menu? • app icon automatically added – we don’t need to declare it in the menu XML • same for the view menu, but in this case we need to configure and populate it from Java code – items added at run time (later lecture) Activity Lifecycle 48 The Action Bar Can configure aspects in Java code private void setUpActionBar() { final ActionBar actionBar = getActionBar(); actionBar.setDisplayShowTitleEnabled(false); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST); } • don’t show the app title (just the icon) • make the view navigation a list (menu) • the alternative is tabs, which isn’t really appropriate here Activity Lifecycle 49 The Action Bar Ooops • remember the Action Bar was introduced in Android 3.0 (API level 11) • change AndroidManifest.xml • android:minSdkVersion="11" Activity Lifecycle 50 Homework Read • http://developer.android.com/tools/help/logcat.html • http://developer.android.com/guide/components/ activities.html • http://developer.android.com/guide/topics/ui/ actionbar.html Override all activity lifecycle methods in the PropertyFinderActivity, output a log message for each, investigate when each method is called Activity Lifecycle 51 Next List views and adapters Fragments Activity Lifecycle 52