Getting Started Dr. Miguel A. Labrador Department of Computer Science & Engineering labrador@csee.usf.edu http://www.csee.usf.edu/~labrador 1
Goals Setting up your development environment Android Framework and Components Building your first app Adding the action bar Managing the activity lifecycle Note: All these lecture notes have been taken from http://developer.android.com/training/index.html 2 2
3 Setting Up Your Development Environment
Setting up your environment Download and install the Java Development Kit (JDK) http://www.oracle.com/technetwork/java/javase/downloads/jdk8- downloads-2133151.html Download and install Android Studio http://developer.android.com/sdk/index.html Run Android Studio Download the latest SDK tools and platforms Go to Tools->Android->SDK Manager 4 4
5 5
Android SDK In Tools, select the following options: Android SDK Tools Android SDK Platform-tools Android SDK Build-tools In the first Android X.X folder, select: SDK Platform A system image for the emulator, such as ARM EABI v7a System Image In the Extras directory, select: Android Support Repository Android Support Library Google Repository Google Play Services Install all the selected packages 6 6
7 Android Framework and Components
Android Framework 8 8
Android Application Components Android applications consist of loosely coupled components, bound by an application manifest that describes each component and how they interact, as well as the hardware and platform requirements Android consists of the following seven components Activities Every screen in your application is an extension of the Activity class Activities use Views to form GUIs Services Run in the background, updating your data sources and visible Activities and triggering Notifications Used to perform regular processing that needs to continue even when your application s Activities are not active or visible 9 9
Android Application Components Content Providers Sharable data stores used to manage and share application databases Intents An inter-application message-passing framework Using Intents you can broadcast messages system-wide or to a target Activity or Service Broadcast Receivers Intent broadcast consumers If you create and register a Broadcast Receiver, your application can listen for broadcast Intents BR will automatically start your application to respond to an incoming Intent Good for creating event-driven applications 10 10
Android Application Components Widgets Visual application components that can be added to the home screen Notifications A user notification framework Let you signal users without interrupting their current Activities Preferred method for getting a user s attention from within a Service or Broadcast Receiver Incoming phone call signal 11 11
12 Building Your First App
Building Your First App Creating an Android Project Running your application Building a simple user interface Starting another activity 13 13
Creating an Android Project 14 In Android Studio, click on File->New Project Fill the fields in the Configure your new project Application name: My First App Company domain: labrador.cse.usf.edu Package name Fully qualified name for the project Follows Java naming conventions Must be unique across all packages Project location Next Where your project files will be stored 14
Creating an Android Project Select the form factors your app will run on Phone and tablet Minimum SDK: select API 8: Android 2.2 (Froyo) Next The Minimum Required SDK is the earliest version of Android that your app supports 15 15
Creating an Android Project Under Add an activity to <template>: select Blank Activity Next Under choose options for your new file Change Activity Name to MyActivity The layout name changes to activity_my and the Title to MyActivity The menu Resource Name is menu_my Finish Your Android project is now a basic Hello World app that contains some default files 16 16
17 17
Android Default Files 18 app/src/main/res/layout/activity_my.xml This is the XML layout file for the activity you added app/src/main/java/com.mycompany.myfirstapp/myactivity.java The class definition for the activity you created When you build and run the app, the Activity class starts the activity and loads the layout file that says "Hello World!" app/src/main/androidmanifest.xml Describes the fundamental characteristics of the app and defines each of its components app/build.gradle Android Studio uses Gradle to compile and build your app Usually, you're only interested in the build.gradle file for the module, in this case the app or application module. This is where your app's build dependencies are set, including the defaultconfig settings 18
Android Default Files defaultconfig settings compiledsdkversion is the platform version against which you will compile your app By default, this is set to the latest version of Android available in your SDK. (It should be Android 4.1 or greater; if you don't have such a version available, you must install one using the SDK Manager) applicationid is the fully qualified package name for your application that you specified during the New Project workflow minsdkversion is the Minimum SDK version you specified during the New Project workflow This is the earliest version of the Android SDK that your app supports targetsdkversion indicates the highest version of Android with which you have tested your application 19 19
20 Android Default Files the /res subdirectories that contain the resources for your application drawable<density>/ Directories for drawable objects (such as bitmaps) that are designed for various densities, such as medium-density (mdpi) and high-density (hdpi) screens layout/ Directory for files that define your app's user interface like activity_my.xml, discussed above, which describes a basic layout for the MyActivity class menu/ Directory for files that define your app's menu items values/ Directory for other XML files that contain a collection of resources, such as string and color definitions. The strings.xml file defines the "Hello world!" string that displays when you run the default app 20
Manifest <?xml version="1.0" encoding="utf-8"?> -<manifest package="com.labrador.miguel.myfirstapp" xmlns:android="http://schemas.android.com/apk/res/android"> -<application android:theme="@style/apptheme" android:label="@string/app_name" android:icon="@mipmap/ic_launcher" android:allowbackup="true"> -<activity android:label="@string/app_name" android:name=".myactivity"> -<intent-filter> <action android:name="android.intent.action.main"/> <category android:name="android.intent.category.launcher"/> </intent-filter> </activity> -<activity android:label="@string/title_activity_display_message" android:name=".displaymessageactivity" android:parentactivityname=".myactivity"> <meta-data android:name="android.support.parent_activity" android:value="com.labrador.miguel.myfirstapp.myactivity"/> </activity> </application> </manifest> 21 21
Strings <?xml version="1.0"?> <resources><string name="app_name">my First App</string><string name="edit_message">enter a message</string><string name="button_send">send</string><string name="action_settings">settings</string><string name="action_search">search</string><string name="title_activity_main">mainactivity</string><string name="title_activity_display_message">my Message</string> <string name="hello_world">hello world!</string> </resources> 22 22
Layout <?xml version="1.0" encoding="utf-8"?> <LinearLayout android:orientation="vertical" android:layout_height="fill_parent" android:layout_width="fill_parent" xmlns:android="http://schemas.android.com/apk/res/android" ><TextView android:layout_height="wrap_content" android:layout_width="wrap_content" android:id="@+id/textview" android:text="@string/hello_world"/> </LinearLayout> 23 23
Activity public class MyActivity extends AppCompatActivity { } public final static String EXTRA_MESSAGE = "com.mycompany.myfirstapp.message"; @Override public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_my); 24 24
25 Run it on the Emulator Create an AVD Running Your App Launch the Android Virtual Device Manager In Android Studio, select Tools > Android > AVD Manager, or click the AVD Manager icon in the toolbar On the AVD Manager main screen, click Create Virtual Device In the Select Hardware window, select a device configuration, such as Nexus 6, then click Next Select the desired system version for the AVD and click Next Verify the configuration settings, then click Finish In Android Studio, select your project and click Run from the toolbar In the Choose Device window, click the Launch emulator radio button From the Android virtual device pull-down menu, select the emulator you created, and click OK 25
Run it on a real device Set up your device Running Your App Plug in your device to your development machine with a USB cable If you're developing on Windows, you might need to install the appropriate USB driver for your device Enable USB debugging on your device On most devices running Android 3.2 or older, you can find the option under Settings > Applications > Development On Android 4.0 and newer, it's in Settings > Developer options Run the app from Android Studio Click Run from the toolbar In the Choose Device window that appears, select the Choose a running device radio button, select your device, and click OK Android Studio installs the app on your connected device and starts it 26 26
27 27
Building a Simple User Interface In this part, you will create a layout in XML that includes a text field and a button In the next part, your app responds when the button is pressed by sending the content of the text field to another activity 28 28
Building a Simple User Interface The graphical user interface for an Android app is built using a hierarchy of View and ViewGroup objects. View objects are usually UI widgets Layouts are subclasses of the ViewGroup Here, you will work with a LinearLayout In Android Studio, from the res/layout directory, open the activity_my.xml file The BlankActivity template you chose when you created this project includes the activity_my.xml file with a RelativeLayout root view and a TextView child view 29 29
Creating a New Layout <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 30 android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal"> <EditText android:id="@+id/edit_message" android:layout_weight="1" android:layout_width="0dp" android:layout_height="wrap_content" android:hint="@string/edit_message" /> <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/button_send" /> </LinearLayout> 30
Creating a New Layout Add String Resources By default, your Android project includes a string resource file at res/values/strings.xml. Here, you'll add a new string named "edit_message" and set the value to "Enter a message Add a line for a string named "button_send" with the value, "Send Remove the line for the "hello world" string 31 <?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">my First App</string> <string name="edit_message">enter a message</string> <string name="button_send">send</string> <string name="action_settings">settings</string> <string name="title_activity_main">mainactivity</string> </resources> 31
Starting Another Activity 32 Creating a new activity In Android Studio, in the java directory, select the package, edu.usf.cse.labrador.myfirstapp, right-click, and select New > Activity > Blank Activity In the Choose options window, fill in the activity details Activity Name: DisplayMessageActivity Layout Name: activity_display_message Title: My Message Hierarchical Parent: edu.usf.cse.labrador.myfirstapp.myactivity Package name: edu.usf.cse.labrador.myfirstapp Click Finish Open the DisplayMessageActivity.java file The class already includes an implementation of the required oncreate() method. Remove the oncreateoptionsmenu() method. You won't need it for this app 32
Starting Another Activity If you open the strings.xml and AndroidManifest.xml files you will notice that Android Studio automatically modified those files to register the new activity and include its title 33 33
Respond to the Send Button public class MyActivity extends AppCompatActivity { public final static String EXTRA_MESSAGE = "com.mycompany.myfirstapp.message"; @Override public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_my); } Button send = (Button) this.findviewbyid(r.id.button1); send.setonclicklistener(new View.OnClickListener() { @Override public void onclick(view view) { sendmessage(view); } }); 34 34
Building an Intent and Passing the Data /** Called when the user clicks the Send button */ public void sendmessage(view view) { Intent intent = new Intent(this, DisplayMessageActivity.class); Bundle bundle = new Bundle(); EditText edittext = (EditText) findviewbyid(r.id.edit_message); String message = edittext.gettext().tostring(); bundle.putstring("extra_message", message); intent.putextras(bundle); startactivity(intent); } 35 35
Receive the Intent and Display the Data public class DisplayMessageActivity extends AppCompatActivity { String receivedmessage; @Override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); // Get the message from the intent Bundle b = getintent().getextras(); receivedmessage = b.getstring("extra_message"); // Create the text view TextView textview = new TextView(this); textview.settextsize(40); textview.settext(receivedmessage); // Set the text view as the activity layout setcontentview(textview); getsupportactionbar().setdisplayhomeasupenabled(true); 36 } 36
37 37
38 Managing the Activity Life Cycle
Managing the Activity Life Cycle As a user navigates through, out of, and back to your app, the Activity instances in your app transition between different states in their lifecycle Within the lifecycle callback methods, you can declare how your activity behaves when the user leaves and re-enters the activity For example, if you're building a streaming video player, you might pause the video and terminate the network connection when the user switches to another app When the user returns, you can reconnect to the network and allow the user to resume the video from the same spot 39 39
Android Activity Lifecycle 40 Taken from: http://developer.android.com/training/basics/activity-lifecycle/index.html 40
41 Managing the Activity Lifecycle Only three of these states can be static Resumed The activity is in the foreground and the user can interact with it Paused The activity is partially obscured by another activity. The paused activity does not receive user input and cannot execute any code Stopped The activity is completely hidden and not visible to the user; it is considered to be in the background. While stopped, the activity instance and all its state information such as member variables is retained, but it cannot execute any code The other states (Created and Started) are transient and the system quickly moves from them to the next state by calling the next lifecycle callback method After the system calls oncreate(), it quickly calls onstart(), which is quickly followed by onresume() 41
Managing the Activity Lifecycle When the user selects your app icon from the Home screen, the system calls the oncreate() method for the Activity in your app that you've declared to be the "launcher" (or "main") activity You can define which activity to use as the main activity in the Android manifest file 42 42
Managing the Activity Lifecycle Depending on the complexity of your activity, you probably don't need to implement all the lifecycle methods. However, it's important that you understand each one and implement those that ensure your app behaves the way users expect: Does not crash if the user receives a phone call or switches to another app while using your app Does not consume valuable system resources when the user is not actively using it Does not lose the user's progress if they leave your app and return to it at a later time Does not crash or lose the user's progress when the screen rotates between landscape and portrait orientation 43 43
44 Pausing Your Activity During normal app use, the foreground activity is sometimes obstructed by other visual components that cause the activity to pause For example, when a semi-transparent activity opens (such as one in the style of a dialog), the previous activity pauses. As long as the activity is still partially visible but currently not the activity in focus, it remains paused Once the activity is fully-obstructed and not visible, it stops You should usually use the onpause() callback to: Stop animations or other ongoing actions that could consume CPU Commit unsaved changes, but only if users expect such changes to be permanently saved when they leave (such as a draft email) Release system resources, such as broadcast receivers, handles to sensors (like GPS), or any resources that may affect battery life while your activity is paused and the user does not need them 44
Resuming Your Activity When the user resumes your activity from the Paused state, the system calls the onresume() method Be aware that the system calls this method every time your activity comes into the foreground, including when it's created for the first time You should implement onresume() to initialize components that you released during onpause() and perform any other initializations that must occur each time the activity enters the Resumed state 45 45
Stopping Your Activity There are a few of key scenarios in which your activity is stopped and restarted: The user opens the Recent Apps window and switches from your app to another app. The activity in your app that's currently in the foreground is stopped. If the user returns to your app from the Home screen launcher icon or the Recent Apps window, the activity restarts The user performs an action in your app that starts a new activity. The current activity is stopped when the second activity is created. If the user then presses the Back button, the first activity is restarted The user receives a phone call while using your app 46 46
Start/Restart Your Activity It's uncommon that an app needs to use onrestart() to restore the activity's state, so there aren't any guidelines for this method that apply to the general population of apps Because your onstop() method should essentially clean up all your activity's resources, you'll need to re-instantiate them when the activity restarts You also need to instantiate them when your activity is created for the first time (when there's no existing instance of the activity) For this reason, you should usually use the onstart() callback method as the counterpart to the onstop() method, because the system calls onstart() both when it creates your activity and when it restarts the activity from the stopped state 47 47
Destroy Your Activity When the system destroys your activity, it calls the ondestroy() method Because you should generally have released most of your resources with onstop(), by the time you receive a call to ondestroy(), there's not much that most apps need to do This method is your last chance to clean out resources that could lead to a memory leak If your activity includes background threads that you created during oncreate() or other long-running resources that could potentially leak memory if not properly closed, you should kill them during ondestroy() 48 48