Activities and Intents Chapter 3 1. Objectives Explore an activity’s lifecycle Learn about saving and restoring an activity Understand intents and how.

Slides:



Advertisements
Similar presentations
Programming with Android: Activities and Intents
Advertisements

CE881: Mobile and Social Application Programming Simon M. Lucas Quiz, Walkthrough, Exercise, Lifecycles, Intents.
Programming with Android: Activities and Intents Luca Bedogni Marco Di Felice Dipartimento di Scienze dell’Informazione Università di Bologna.
Programming with Android: Activities and Intents Luca Bedogni Marco Di Felice Dipartimento di Informatica – Scienza e Ingegneria Università di Bologna.
CSE2102 Introduction to Software Engineering Lab 2 Sept/4/2013.
Programming with Android: Activities
Android 02: Activities David Meredith
All About Android Introduction to Android 1. Creating a New App “These aren’t the droids we’re looking for.” Obi-wan Kenobi 1. Bring up Eclipse. 2. Click.
The Android Activity Lifecycle. Slide 2 Introduction Working with the Android logging system Rotation and multiple layouts Understanding the Android activity.
Manifest File, Intents, and Multiple Activities. Manifest File.
The Activity Class 1.  One application component type  Provides a visual interface for a single screen  Typically supports one thing a user can do,
Application Fundamentals. See: developer.android.com/guide/developing/building/index.html.
Android Life Cycle CS328 Dick Steflik. Life Cycle The steps that an application goes through from starting to finishing Slightly different than normal.
More on User Interface Android Applications. Layouts Linear Layout Relative Layout Table Layout Grid View Tab Layout List View.
Chien-Chung Shen Manifest and Activity Chien-Chung Shen
CS378 - Mobile Computing Anatomy of an Android App and the App Lifecycle.
© Keren Kalif Intro to Android Development Written by Keren Kalif, Edited by Liron Blecher Contains slides from Google I/O presentation.
ANDROID UI – FRAGMENTS. Fragment  An activity is a container for views  When you have a larger screen device than a phone –like a tablet it can look.
Software Architecture of Android Yaodong Bi, Ph.D. Department of Computing Sciences University of Scranton.
Android Mobile computing for the rest of us.* *Prepare to be sued by Apple.
CS378 - Mobile Computing Intents.
Activities and Intents. Activities Activity is a window that contains the user interface of your application,typically an application has one or more.
Copyright© Jeffrey Jongko, Ateneo de Manila University Of Activities, Intents and Applications.
CS378 - Mobile Computing Intents. Allow us to use applications and components that are part of Android System – start activities – start services – deliver.
Understand applications and their components activity service broadcast receiver content provider intent AndroidManifest.xml.
Android – Fragments L. Grewe.
Mobile Programming Lecture 5 Composite Views, Activities, Intents and Filters.
Cosc 5/4730 Android Communications Intents, callbacks, and setters.
Linking Activities using Intents How to navigate between Android Activities 1Linking Activities using Intents.
Noname. Conceptual Parts States of Activities Active Pause Stop Inactive.
Activity Android Club Agenda Hello Android application Application components Activity StartActivity.
1 CMSC 628: Introduction to Mobile Computing Nilanjan Banerjee Introduction to Mobile Computing University of Maryland Baltimore County
Applications with Multiple Activities. Most applications will have more than one activity. The main activity is started when the application is started.
Working with Multiple Activities. Slide 2 Introduction Working with multiple activities Creating multiple views Introduction to intents Passing data to.
Introducing Intents Intents Bind application components and navigate between them Transform device into collection of interconnected systems Creating a.
Intents 1 CS440. Intents  Message passing mechanism  Most common uses:  starting an Activity (open an , contact, etc.)  starting an Activity.
Lecture 2: Android Concepts
Technische Universität München Services, IPC and RPC Gökhan Yilmaz, Benedikt Brück.
Intents and Broadcast Receivers Dr. David Janzen Except as otherwise noted, the content of this presentation is licensed under the Creative Commons Attribution.
Services. What is a Service? A Service is not a separate process. A Service is not a thread. A Service itself is actually very simple, providing two main.
School of Engineering and Information and Communication Technology KIT305/KIT607 Mobile Application Development Android OS –Permissions (cont.), Fragments,
Working with Multiple Activities. Slide 2 Introduction Working with multiple activities Putting together the AndroidManifest.xml file Creating multiple.
CS371m - Mobile Computing Intents 1. Allow us to use applications and components that are already part of Android System – start activities – start services.
Android Application -Architecture.
Lecture 2: Android Concepts
Mobile Application Development BSCS-7 Lecture # 2
Activity and Fragment.
Programming with Android:
Activities, Fragments, and Events
Activities and Intents
Anatomy of an Android App and the App Lifecycle
Android Mobile Application Development
The Android Activity Lifecycle
ANDROID UI – FRAGMENTS UNIT II.
CIS 470 Mobile App Development
Anatomy of an Android App and the App Lifecycle
Activity Lifecycle Fall 2012 CS2302: Programming Principles.
Activities and Intents
Activities and Intents
HNDIT2417 Mobile Application Development
CIS 470 Mobile App Development
Activities and Intents
Objects First with Java
Activities and Intents
SE4S701 Mobile Application Development
Lecture 2: Android Concepts
Activities and Fragments
Android Development Tools
Activities, Fragments, and Intents
CIS 694/EEC 693 Android Sensor Programming
Presentation transcript:

Activities and Intents Chapter 3 1

Objectives Explore an activity’s lifecycle Learn about saving and restoring an activity Understand intents and how they are used with multiple activities Become familiar with passing data between activities Implement applications that require basic animation activity transitions Study scene transitions 2

Overview Activity Units or building blocks of Android applications in that an app is made up of zero or more activities Container for UI, holding UI as well as the code that runs it; controller in MVC Q: how to associate a UI with an activity? Run on its own VM Q: Why? Advantages/disadvantages? Intent Glue for connecting activities that run on different VMs 3 VM Activity 1 Activity 2 VM intent

Activity Declaration Defined as a subclass of android.app.Activity Declared in the AndroidManifest.xml file Q: Why? to be accessible to the system Use the tag Must be a child of the element One designated as the main activity … 4

Activity Management In most cases, apps are composed of multiple activities. With one serving as the main (entry) activity Often loosely connected to each other Information passed from one activity to another But remain distinct and separate in every other way 5

Activity Stack The activities in an application are managed by the Android system using an activity stack (similar to call stack). Each time a new activity starts, the previous activity is paused and its status is preserved. New activities are pushed onto the top of the stack and become the running activity. VM A1 invoke VM A2 VM A3 invoke A1 A2 A3 6 running paused activity stack

Activity Lifecycle Determine an app’s overall lifecycle Managed by the Android system by providing seven callback methods (defined in Activity class), beginning with the creation of the activity and ending with its destruction onCreate() onStart() onResume() onPause() onStop() onRestart() onDestroy() 7 *Read API doc of the Activity class

Lifecycle Methods onCreate(): when created first or recreated if a paused or stopped activity requires destruction due to a system need for more memory, the activity will need to be recreated again. onStart(): when becoming visible; always to be called after onRestart() onStop(): when becoming no longer visible to the user onDestroy(): performs final cleanup prior to an activity’s destruction 8

9

Lab 3-1 Activity Lifecycle App Pages Or extend the Timer App by overriding lifecycle methods to find sequences of calls when: 1.The app is first launched 2.The Home button is clicked 3.It is restarted from the launcher 4.The Previous button is clicked 5.It is restarted from the launcher 6.The device is rotated (CTRL-[ALT]-F11 on AVD) 10

Saving and Restoring an Activity When an activity is paused or stopped, the state of the activity is retained When the system destroys an activity in order to recover memory, the memory for that activity object is also destroyed 11

Saving and Restoring (Cont.) A Bundle is a container for the activity state information that can be saved putInt(String, int) getInt(String), … Recover the saved state from the Bundle that the system passes to the activity onCreate(Bundle) and onRestoreInstanceState(Bundle) Check whether the activity’s state (stored in the Bundle object) is null before you attempt to read it If it is null, then the system is creating a new instance, instead of restoring a previous one that was destroyed 12

Screen Orientation Change Activity behavior when orientation changes onCreate -> onStart -> onResume... onDestroy <- onStop <- onPause -> onCreate -> onStart -> onResume... What about activity state? Only named views (via the android:id attribute) in an activity will have their states persisted. 13

Screen Orientation Change Activity behavior when orientation changes onCreate -> onStart -> onResume... onDestroy <- onStop <- onPause -> onCreate -> onStart -> onResume... What about activity state? Only named views (via the android:id attribute) in an activity will have their states persisted. 14

Persisting State Information Two possible events upon activity kills onPause(): always fired onSaveInstanceState(Bundle): not fired when activity is unloaded from the stack (e.g., when the Back button is pressed; no reason to store) *Bundle from onSaveInstanceState is also available to onCreate(Bundle) 15 protected void onSaveInstanceState(Bundle outState) { outState.putString("ID", "1234"); super.onSaveInstanceState(outState); // Q: why? } // called when activity is re-recreated, following onCreate(). protected void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); // Q: why? String ID = savedInstanceState.getString("ID"); }

Lab: Improved Timer App Extend the Timer app to handle screen orientation changes, i.e., not to reset to 0 Use onSave/RestoreInstanceState() May need to extend the TimerModel class Lifecyle: onPause -> onSave* -> onStop -> onDestroy onResume <- onRestore* <- onStart <- onCreate <-+ 16

Intents Glue for connecting activities (possibly from different apps) that may run on different VMs Apps built with multiple activities need to utilize the Intent class. This class provides the framework for the navigation from one screen to another. An Intent object is a message from one component to another component, either within the app or outside the app. Designed to communicate messages between three application core components: Activities Broadcast receivers Services 17

Explicit vs. Implicit Intents Explicit Specify a specific activity class Only for activities defined within the same app Implicit Specifies an action along with data For activities defined within or outside the app 18 startActivity(new Intent(this, SecondActivity.class); startActivity(new Intent(android.content.Intent.ACTION_DIAL, Uri.parse("tel: ")));

Linking Activities with Explicit Intents 1.Create a new activity, say SecondActivity, including its UI 2.Declare it in AndroidManifest.xml 3.Start the new activity 19 <application... … // from main activity public void onClick(View view) { startActivity(new Intent(this, SecondActivity.class)); } *Q: startActivity similar to method call?

Implicit Intents Unlike an explicit intent, an implicit Intent does not name a specific component. It declares a general action to perform, which allows a component from another app to handle it. When an implicit intent is created, the system locates the appropriate target component by comparing the contents of the intent to an intent filter. Intent filters are declared in the manifest file of other apps located on a given device. When the intent has found a match with an intent filter, the system starts that component and delivers the intent object to it. 20

Declaring Intent Filters 21 <application... … Action: to be called by other activities Convention: Use reverse domain name Category: group activities User-defined categories possible DEFAULT: to be called using startActivity()

Linking with Implicit Intents 22 public void onClick(View view) { startActivity(new Intent("edu.utep.cs.cs4330.PLAY")); } Can add a category to an intent to find an activity belonging to that category, e.g., Intent i = new Intent("..."); i.addCategory("edu.utep.cs.cs4330.FUN_GAME"); Resolving intent filter collision What happen if there exist more than one activities with the same intent filter name? => Android OS will let you select one by displaying a selection dialog

Calling Built-in Apps Using Intents Use intents to call activities from other apps, including built-ins, e.g., call a person using the Contacts app. Benefits? Consistent user experience Avoid building another duplicate app How? In intent, specify action along with data Intent resolution: process performed by Android OS to look for all activities that are able to satisfy an intent In sum, an action-and-data pair describes the operation to be performed 23

Standard Activity Actions 24 ActionExample Browse a website Intent i = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse(" startActivity(i); Dial a number startActivity(new Intent(android.content.Intent.ACTION_DIAL, Uri.parse("tel: "))); Show a map Intent i = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse("geo: , "); startActivity(i); Choose a contact Intent i = new Intent(android.content.Intent.ACTION_PICK); i.setType(ContactsContract.Contacts.CONTENT_TYPE); startActivityForRessult(i, requestCode); *Many predefined actions and categories; read API doc of the Intent class. *Uniform Resource Identifier (URI): a string to identify a name or a resource, e.g., URL

Lab: Launcher App Create an app with two buttons for launching: Timer app from previous lab Built-in Dialer (Phone) app Hint: An activity may have more than one intent filter. 25

Passing Data Between Activities Issues Activities run on different VMs (no global variables) Asynchronous invocation (no return point) Solution  : Piggyback on intent  : Use intent and callback 26 VM Activity 1 Activity 2 VM ?

Sending Data to Invoked Activity Piggyback on the intent 27 // calling activity Intent i = new Intent("edu.utep.cs.cs4330.PLAY"); Bundle extras = new Bundle(); extras.putString(“course", “CS 4330"); i.putExtras(extras); startActivity(i); // called activity String course = null; Bundle extras = getIntent().getExtras(); if (extras != null) { course= extras.getString(“course"); } *Numerous helper methods defined on Intent, e.g., putExtra and getStringExtra. Bundle extras intent Activity getIntent() Intent getExtras()

Returning Results Use callback (Observer pattern) Q: Why request code? 28 // calling activity Intent i = new Intent(“edu.utep.cs.cs4330.PLAY"); startActivityForResult(i, 1); // 1: request code protected void onActivityResult(int requestCode, int resultCode, Intent result) { if (requestCode == 1 && resultCode == RESULT_OK) {... result.getData().toString()... // Uri getData() } // called activity Intent result = new Intent(); result.setData(Uri.parse("Here's the result!")); // Intent setData(Uri) setResult(RESULT_OK, result); finish(); // close the activity and give control to the invoking activity

Activity and Intent Classes 29 Bundle extras intent Uri Activity getIntent() onActivityResult(int, int, Intent) setResult(Intent) finish() Intent setExtras(Bundle) getExtras() setData(Uri) getData() data result

Lab 3-3 Auto Loan Calculator Pages App consisting of two activities 30

Lab: MyGrade App 31 App to inquire CS 4330 grade Two activities: MainActivity and HelperActivity Source files from course website

Activity Transitions Judicious use of animation can enhance the usability of an app by providing engaging and dynamic UI. Basic transition Custom transition animation between activities Use overridePendingTransition() Entering/exiting animation defined in XML Lab 3-4: Flip Cards Scene transition Since KitKat (Android 4.4) Lab 3-5: Pieces of a Painting 32