Basics of Android Development 1

Similar documents
Android Basics. Xin Yang

Getting Started: Creating a Simple App

Mono for Android Activity Lifecycle Activity Lifecycle Concepts and Overview

How To Develop Android On Your Computer Or Tablet Or Phone

Android Development. Marc Mc Loughlin

Building Your First App

Android Fundamentals 1

INTRODUCTION TO ANDROID CSCI 4448/5448: OBJECT-ORIENTED ANALYSIS & DESIGN LECTURE 11 02/15/2011

Developing NFC Applications on the Android Platform. The Definitive Resource

Android Programming. Høgskolen i Telemark Telemark University College. Cuong Nguyen,

Introduction to Android Programming (CS5248 Fall 2015)

AndroLIFT: A Tool for Android Application Life Cycles

Android Java Live and In Action

Mobile Security - Tutorial 1. Beginning Advanced Android Development Brian Ricks Fall 2014

Admin. Mobile Software Development Framework: Android Activity, View/ViewGroup, External Resources. Recap: TinyOS. Recap: J2ME Framework

Android Application Development

App Development for Smart Devices. Lec #2: Android Tools, Building Applications, and Activities

Introduction to Android. CSG250 Wireless Networks Fall, 2008

Android For Java Developers. Marko Gargenta Marakana

Introduction to Android: Hello, Android! 26 Mar 2010 CMPT166 Dr. Sean Ho Trinity Western University

ECWM511 MOBILE APPLICATION DEVELOPMENT Lecture 1: Introduction to Android

How to develop your own app

Android Application Development - Exam Sample

Q1. What method you should override to use Android menu system?

ELET4133: Embedded Systems. Topic 15 Sensors

Now that we have the Android SDK, Eclipse and Phones all ready to go we can jump into actual Android development.

Lab 1 (Reading Sensors & The Android API) Week 3

Android Application Model

Detecting privacy leaks in Android Apps

A Short Introduction to Android

Università Degli Studi di Parma. Distributed Systems Group. Android Development. Lecture 2 Android Platform. Marco Picone

Introduction to Android Development. Jeff Avery CS349, Mar 2013

Android Application Development: Hands- On. Dr. Jogesh K. Muppala

Tutorial #1. Android Application Development Advanced Hello World App

Android Development Exercises Version Hands On Exercises for. Android Development. v

Login with Amazon Getting Started Guide for Android. Version 2.0

An Introduction to Android Application Development. Serdar Akın, Haluk Tüfekçi

Android Developer Fundamental 1

Developing Android Applications Introduction to Software Engineering Fall Updated 7 October 2015

IOIO for Android Beginners Guide Introduction

Android Studio Application Development

Frameworks & Android. Programmeertechnieken, Tim Cocx

Mobile Application Development Android

TomTom PRO 82xx PRO.connect developer guide

Publishing, Analytics and Ads

Creating a List UI with Android. Michele Schimd

06 Team Project: Android Development Crash Course; Project Introduction

Mobile Application Development 2014

ANDROID APPS DEVELOPMENT FOR MOBILE AND TABLET DEVICE (LEVEL I)

Android 多 核 心 嵌 入 式 多 媒 體 系 統 設 計 與 實 作

Android Development. 吳 俊 興 國 立 高 雄 大 學 資 訊 工 程 學 系

directory to "d:\myproject\android". Hereafter, I shall denote the android installed directory as

OpenCV on Android Platforms

Android Environment SDK

Beginner s Android Development Tutorial!

Getting Started with Android Programming (5 days) with Android 4.3 Jelly Bean

Appium mobile test automation

Xamarin Android Application Development

Android Environment SDK

BIGPOND ONLINE STORAGE USER GUIDE Issue August 2005

TUTORIAL. BUILDING A SIMPLE MAPPING APPLICATION

Compiler Setup and DirectX/OpenGL Setup

Android Tutorial. Larry Walters OOSE Fall 2011

Lab 3 It s all about data - the Android SQLite Database

Android Security Lab WS 2014/15 Lab 1: Android Application Programming

Programming with Android

Operating System Support for Inter-Application Monitoring in Android

Developer's Cookbook. Building Applications with. The Android. the Android SDK. A Addison-Wesley. James Steele Nelson To

ANDROID PROGRAMMING - INTRODUCTION. Roberto Beraldi

Developing In Eclipse, with ADT

Salesforce Mobile Push Notifications Implementation Guide

Programming with Android: System Architecture. Dipartimento di Scienze dell Informazione Università di Bologna

Android Concepts and Programming TUTORIAL 1

Android App Development Lloyd Hasson 2015 CONTENTS. Web-Based Method: Codenvy. Sponsored by. Android App. Development

Android on Intel Course App Development - Advanced

Chapter 2 Getting Started

Generate Android App

23442 ECE Introduction to Android Mobile Programming ECE Special Topics: Android Mobile Programming

2. Click the download button for your operating system (Windows, Mac, or Linux).

Developing an Android App. CSC207 Fall 2014

A model driven approach for Android applications development

Mocean Android SDK Developer Guide

Getting Started With Android

Spring Design ScreenShare Service SDK Instructions

How to test and debug an ASP.NET application

Android Programming Basics

Jordan Jozwiak November 13, 2011

Transcription:

Departamento de Engenharia Informática Minds-On Basics of Android Development 1 Paulo Baltarejo Sousa pbs@isep.ipp.pt 2016 1 The content of this document is based on the material presented at http://developer.android.com

1 Activities An activity provides a user interface for a single screen in your app. Activities can move into the background and then be resumed with their state restored An app usually consists of multiple activities that are loosely bound to each other. Typically, one activity in an app is specified as the "main" activity, which is presented to the user when launching the app for the first time. Each activity can then start another activity in order to perform different actions. Each time a new activity starts, the previous activity is stopped, but the system preserves the activity in a stack (the "back stack"). When a new activity starts, it is pushed onto the back stack and takes user focus. The back stack abides to the basic "last in, first out" stack mechanism, so, when the user is done with the current activity and presses the Back button, it is popped from the stack (and destroyed) and the previous activity resumes. (The back stack is discussed more in the next section) When an activity is stopped because a new activity starts, it is notified of this change in state through the activity s lifecycle callback methods. There are several callback methods that an activity might receive, due to a change in its state whether the system is creating it, stopping it, resuming it, or destroying it, and each callback provides you the opportunity to perform specific work that s appropriate to that state change. For instance, when stopped, your activity should release any large objects, such as network or database connections. When the activity resumes, you can reacquire the necessary resources and resume actions that were interrupted. These state transitions are all part of the activity lifecycle. 2 Tasks and Back Stack An app usually contains multiple activities. Each activity should be designed around a specific kind of action the user can perform and can start other activities. For example, an email app might have one activity to show a list of new email. When the user selects an email, a new activity opens to view that email. An activity can even start activities that exist in other apps on the device. For example, if your app wants to send an email, you can define an intent to perform a "send" action and include some data, such as an email address and a message. An activity from another app that declares itself to handle this kind of intent then opens. In this case, the intent is to send an email, so an email app s "compose" activity starts (if multiple activities support the same intent, then the system lets the user select which one to use). When 1

the email is sent, your activity resumes and it seems as if the email activity was part of your app. Even though the activities may be from different apps, Android maintains this seamless user experience by keeping both activities in the same task. A task is a collection of activities that users interact with when performing a certain job. The activities are arranged in a stack (the "back stack"), in the order in which each activity is opened. The device Home screen is the starting place for most tasks. When the user touches an icon in the app launcher (or a shortcut on the Home screen), that app s task comes to the foreground. If no task exists for the app (the app has not been used recently), then a new task is created and the "main" activity for that app opens as the root activity in the stack. When the current activity starts another, the new activity is pushed on the top of the stack and takes focus. The previous activity remains in the stack, but is stopped. When an activity stops, the system retains the current state of its user interface. When the user presses the Back button, the current activity is popped from the top of the stack (the activity is destroyed) and the previous activity resumes (the previous state of its UI is restored). Activities in the stack are never rearranged, only pushed and popped from the stack pushed onto the stack when started by the current activity and popped off when the user leaves it using the Back button. As such, the back stack operates as a "last in, first out" object structure. Figure 1 visualizes this behavior with a timeline showing the progress between activities along with the current back stack at each point in time. Fig. 1: Task and back stack. 3 Activity Lifecycle Managing the lifecycle of your activities by implementing callback methods is crucial to developing a strong and flexible app. The lifecycle of an activity 2

is directly affected by its association with other activities, its task and back stack. An activity can exist in essentially three states: Resumed : The activity is in the foreground of the screen and has user focus. (This state is also sometimes referred to as "running".) Paused : Another activity is in the foreground and has focus, but this one is still visible. That is, another activity is visible on top of this one and that activity is partially transparent or doesn t cover the entire screen. A paused activity is completely alive (the Activity object is retained in memory, it maintains all state and member information, and remains attached to the window manager), but can be killed by the system in extremely low memory situations. Stopped : The activity is completely obscured by another activity (the activity is now in the "background"). A stopped activity is also still alive (the Activity object is retained in memory, it maintains all state and member information, but is not attached to the window manager). However, it is no longer visible to the user and it can be killed by the system when memory is needed elsewhere. If an activity is paused or stopped, the system can drop it from memory either by asking it to finish (calling its finish method), or simply killing its process. When the activity is opened again (after being finished or killed), it must be created all over. The activity lifecycle: The entire lifetime of an activity happens between the call to oncreate and the call to ondestroy. Your activity should perform setup of "global" state (such as defining layout) in oncreate, and release all remaining resources in ondestroy. For example, if your activity has a thread running in the background to download data from the network, it might create that thread in oncreate and then stop the thread in ondestroy. The visible lifetime of an activity happens between the call to onstart and the call to onstop. During this time, the user can see the activity on-screen and interact with it. For example, onstop is called when a new activity starts and this one is no longer visible. Between these two methods, you can maintain resources that are needed to show the activity to the user. For example, you can register a BroadcastReceiver in onstart to monitor changes that impact your UI, and unregister it in onstop when the user can no longer see what you are displaying. 3

The system might call onstart and onstop multiple times during the entire lifetime of the activity, as the activity alternates between being visible and hidden to the user. The foreground lifetime of an activity happens between the call to onresume and the call to onpause. During this time, the activity is in front of all other activities on screen and has user input focus. An activity can frequently transition in and out of the foreground, for example, onpause is called when the device goes to sleep or when a dialog appears. Because this state can transition often, the code in these two methods should be fairly lightweight in order to avoid slow transitions that make the user wait. Figure 2 illustrates these loops and the paths an activity might take between states. The rectangles represent the callback methods you can implement to perform operations when the activity transitions between states. Fig. 2: The activity lifecycle. Note that, an activity might be killed when it is on three methods: onpause, onstop, and ondestroy. Because onpause is the first of the three, 4

once the activity is created, onpause is the last method that s guaranteed to be called before the process can be killed? if the system must recover memory in an emergency, then onstop and ondestroy might not be called. Therefore, you should use onpause to write crucial persistent data (such as user edits) to storage. However, you should be selective about what information must be retained during onpause, because any blocking procedures in this method block the transition to the next activity and slow the user experience. 3.1 Creating an Activity To create an activity, you must create a subclass of Activity (or an existing subclass of it). In your subclass, you need to implement callback methods that the system calls when the activity transitions between various states of its lifecycle, such as when the activity is being created, stopped, resumed, or destroyed. The two most important callback methods are: oncreate : You must implement this method. The system calls this when creating your activity. Within your implementation, you should initialize the essential components of your activity. Most importantly, this is where you must call setcontentview to define the layout for the activity s user interface. onpause : The system calls this method as the first indication that the user is leaving your activity (though it does not always mean the activity is being destroyed). This is usually where you should commit any changes that should be persisted beyond the current user session (because the user might not come back). The user interface for an activity is provided by a hierarchy of views?objects derived from the View class. Each view controls a particular rectangular space within the activity s window and can respond to user interaction. For example, a view might be a button that initiates an action when the user touches it. Android provides a number of ready-made views that you can use to design and organize your layout. "Widgets" are views that provide a visual (and interactive) elements for the screen, such as a button, text field, checkbox, or just an image. "Layouts" are views derived from ViewGroup that provide a unique layout model for its child views, such as a linear layout, a grid layout, or relative layout. You can also subclass the View and ViewGroup classes (or existing subclasses) to create your own widgets and layouts and apply them to your activity layout. The most common way to define a layout using views is with an XML layout file saved in your app 5

resources. This way, you can maintain the design of your user interface separately from the source code that defines the activity s behavior. You can set the layout as the UI for your activity with setcontentview, passing the resource ID for the layout. 3.2 Declaring the activity in the manifest You must declare your activity in the manifest file in order for it to be accessible to the system. To declare your activity, open your manifest file and add an <activity> element as a child of the <application> element. For example: < manifest... > < application... > < activity android : name =". ExampleActivity " / >... </ application... >... </ manifest > 3.3 Starting an Activity You can start another activity by calling startactivity, passing it an Intent that describes the activity you want to start. The intent specifies either the exact activity you want to start or describes the type of action you want to perform (and the system selects the appropriate activity for you, which can even be from a different app). An intent can also carry small amounts of data to be used by the activity that is started. When working within your own app, you ll often need to simply launch a known activity. You can do so by creating an intent that explicitly defines the activity you want to start, using the class name. For example, here s how one activity starts another activity named SignInActivity: Intent intent = new Intent ( this, SignInActivity. class ); startactivity ( intent ); 6

4 Implementing a lifecycle Activity app 4.1 Create a project Start a new Android project. 1. Select File > New > New Project... 2. Fill in the project details with the following values: New Project: Application name: Activity Lifecycle Target Android Devices: Phone and Tablet Target Android Devices: Minimum SDK: API10 Add an Activity to Mobile: Empty Activity... 4.2 Implementing callbacks From Android studio, open MainActivity.java file. Implement the following methods: ondestroy onpause onrestart 7

onresume onstart onstop Whenever the name of a method is writing a pop-up window is presented with a list of suggestions. Select one of them. Add a global variable TAG: private static final String TAG="MainActivity:"; Add to each activity lifecycle callbacks the following code: Log.i(getString(R.string.app_name),TAG+"onXXXXX"); The result looks like this: 8

public class MainActivity extends AppCompatActivity { private static final String TAG =" MainActivity :"; protected void oncreate ( Bundle savedinstancestate ) { super. oncreate ( savedinstancestate ); setcontentview ( R. layout. activity_main ); Log.i( getstring (R. string. app_name ),TAG + " oncreate "); protected void onstart () { super. onstart (); Log.i( getstring (R. string. app_name ), TAG + " onstart "); protected void onrestart () { super. onrestart (); Log.i( getstring (R. string. app_name ),TAG + " onrestart "); protected void onresume () { super. onresume (); Log.i( getstring (R. string. app_name ),TAG + " onresume "); protected void onpause () { super. onpause (); Log.i( getstring (R. string. app_name ),TAG + " onpause "); protected void onstop () { super. onstop (); Log.i( getstring (R. string. app_name ), TAG + " onstop "); protected void ondestroy () { super. ondestroy (); Log.i( getstring (R. string. app_name ), TAG + " ondestroy "); Run app and check the LogCat. 4.3 LogCat The Android logging system provides a mechanism for collecting and viewing system debug output. Logs from various apps and portions of the system are collected in a series of circular buffers, which then can be viewed and filtered by the logcat command. You can use logcat to view the log messages. 9

4.4 Adding a new activity 1. Right-click on the package name, select New > Activity > Empty Activity 2. Name the new activity (or accept the name suggestion, Main2Activity). 10

3. Click Finish. This activity creation procedure automatically adds the new activity to the manifest.xml file. Open the Main2Activity.java. 11

Implement the following methods: oncreate ondestroy onpause onrestart onresume onstart onstop Add a global variable TAG: private static final String TAG="Main2Activity:"; Add to each activity lifecycle callbacks the following code: Log.i(getString(R.string.app_name),TAG+"onXXXXX"); The final content of the Main2Activity class is like that: 12

public class Main2Activity extends AppCompatActivity { private static final String TAG =" Main2Activity :"; protected void oncreate ( Bundle savedinstancestate ) { super. oncreate ( savedinstancestate ); setcontentview ( R. layout. activity_main2 ); Log.i( getstring (R. string. app_name ), TAG + " oncreate "); protected void onrestart () { super. onrestart (); Log.i( getstring (R. string. app_name ), TAG + " onrestart "); protected void onstart () { super. onstart (); Log.i( getstring (R. string. app_name ), TAG + " onstart "); protected void onresume () { super. onresume (); Log.i( getstring (R. string. app_name ), TAG + " onresume "); protected void onpause () { super. onpause (); Log.i( getstring (R. string. app_name ), TAG + " onpause "); protected void onstop () { super. onstop (); Log.i( getstring (R. string. app_name ), TAG + " onstop "); protected void ondestroy () { super. ondestroy (); Log.i( getstring (R. string. app_name ), TAG + " ondestroy "); 4.5 Starting one Activity from another Activity Starting Main2Activity from MainActivity by clicking a button. 13

Add a Button element to the activity_main.xml file: <? xml version =" 1.0 " encoding ="utf -8"?> < 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 " android : paddingbottom =" @dimen / activity_vertical_margin " android : paddingleft =" @dimen / activity_horizontal_margin " android : paddingright =" @dimen / activity_horizontal_margin " android : paddingtop =" @dimen / activity_vertical_margin " tools : context ="pt. androiddoc. lifecycle. MainActivity "> < TextView android : layout_width =" wrap_content " android : layout_height =" wrap_content " android : text =" Hello World!" android :id="@+id/ textview "/> < Button android : layout_width =" match_parent " android : layout_height =" wrap_content " android : text =" Open Main2Activity " android :id="@+id/ button " android : layout_below ="@ +id/ textview " android : layout_alignparentleft =" true " android : layout_alignparentstart =" true " android : layout_margintop =" 68 dp" / > </ RelativeLayout > In order to handling the click event on the Button element, code: 14

public class MainActivity extends AppCompatActivity { private static final String TAG =" MainActivity :"; // Event Listener OnClickListener bt_listner = new View. OnClickListener () { // Event handler public void onclick ( View v) { Intent intent = new Intent ( MainActivity. this, Main2Activity. class ); startactivity ( intent ); Log.i( getstring (R. string. app_name ), TAG + " onclick "); ; protected void oncreate ( Bundle savedinstancestate ) { super. oncreate ( savedinstancestate ); setcontentview ( R. layout. activity_main ); Log.i( getstring (R. string. app_name ), TAG + " oncreate "); Button bt = ( Button ) findviewbyid ( R. id. button ); // Register for event listener bt. setonclicklistener ( bt_listner ); protected void onstart () {... protected void onrestart () {... protected void onresume () {... protected void onpause (){... protected void onstop () {... protected void ondestroy () {... 4.6 Running 1. To run the app from Android Studio: Click Run from the toolbar. 15

2. Check the logcat console to learn the Ativity s lifecycle. 16