Cosc 4730 Android GUI. Activity Lifecycle An activity has essentially four states: – If an activity in the foreground of the screen (at the top of the.

Slides:



Advertisements
Similar presentations
Android User Interface
Advertisements

Cosc 5/4730 GUI: layouts, more views, and viewpagers.
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.
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.
Filip Debelić What is it? Android is a mobile operating system (OS) based on the Linux kernel and currently developed by Google Android,
User Interface Android Applications. Activities An activity presents a visual user interface. Each activity is given a default window to draw in. The.
More on User Interface Android Applications. Layouts Linear Layout Relative Layout Table Layout Grid View Tab Layout List View.
Cosc 4730 Android TabActivity and ListView. TabActivity A TabActivity allows for multiple “tabs”. – Each Tab is it’s own activity and the “root” activity.
Android Development (Basics)
Creating Android user interfaces using layouts 1Android user interfaces using layouts.
Chien-Chung Shen Manifest and Activity Chien-Chung Shen
Introduction to Android Programming Content Basic environmental structure Building a simple app Debugging.
Introducing the Sudoku Example
Android: versions Note that: Honeycomb (Android v3.0) A tablet-only release Jelly Bean (Android v4.1) Released on July 09, 2012.
 Understanding an activity  Starting an activity  Passing information between activities  Understanding intents  Understanding the activity lifecycle.
CS5103 Software Engineering Lecture 08 Android Development II.
PROG Mobile Java Application Development PROG Mobile Java Application Development Developing Android Apps: Components & Layout.
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.
Favorite Twitter® Searches App Android How to Program © by Pearson Education, Inc. All Rights Reserved.
Chapter 2: Simplify! The Android User Interface
Tip Calculator App Building an Android App with Java © by Pearson Education, Inc. All Rights Reserved.
Android Layouts. Layouts Define the user interface for an activity Layouts are defined in.xml files – within /res/layout folder – different layout can.
Understanding Hello Android 1 CS300. Activity  Similar to a form  Base class for the visual, interactive components of your application  Android API.
Cosc 5/4730 Introduction: Threads, Android Activities, and MVC.
DUE Hello World on the Android Platform.
1 Announcements Homework #2 due Feb 7 at 1:30pm Submit the entire Eclipse project in Blackboard Please fill out the when2meets when your Project Manager.
Chapter 2 The Android User Interface. Objectives  In this chapter, you learn to:  Develop a user interface using the TextView, ImageView, and Button.
INTRODUCTION TO ANDROID. Slide 2 Application Components An Android application is made of up one or more of the following components Activities We will.
Overview of Android Application Development
User Interfaces: Part 1 (View Groups and Layouts).
Application Development for mobile Devices
Android – Fragments L. Grewe.
Presented By: Muhammad Tariq Software Engineer Android Training course.
Android Boot Camp for Developers Using Java, Comprehensive: A Guide to Creating Your First Android Apps Chapter 2: Simplify! The Android User Interface.
Cosc 5/4730 Basic GUI: Activities, fragments, and Views/Widgets.
Copyright© Jeffrey Jongko, Ateneo de Manila University Basic Views and Layouts.
Cosc 4730 Android Fragments. Fragments You can think of a fragment as a modular section of an activity, which has its own lifecycle, receives its own.
ANDROID – DRAWING IMAGES – SIMPLE EXAMPLE IN INTERFACE AND EVENT HANDLING L. Grewe.
Android Using Menus Notes are based on: The Busy Coder's Guide to Android Development by Mark L. Murphy Copyright © CommonsWare, LLC. ISBN:
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.
HW#9 Clues CSCI 571 Fall, HW#9 Prototype
Copyright© Jeffrey Jongko, Ateneo de Manila University Deconstructing HelloWorld.
ListView and ExpandableListView
CS378 - Mobile Computing User Interface Basics. User Interface Elements View – Control – ViewGroup Layout Widget (Compound Control) Many pre built Views.
Building User Interfaces Basic Applications
Building User Interfaces and Basic Applications Chapter 2 1.
Mobile Programming Lecture 4 Resources, Selection, Activities, Intents.
ANDROID LAYOUTS AND WIDGETS. Slide 2 Introduction Parts of the Android screen Sizing widgets and fonts Layouts and their characteristics Buttons, checkboxes.
Chapter 2: Simplify! The Android User Interface
Lab7 – Appendix.
Android Programming - Features
Open Handset Alliance.
Android Application Development 1 6 May 2018
Activity and Fragment.
Adapting to Display Orientation
Activities and Intents
Mobile Application Development Chapter 4 [Android Navigation and Interface Design] IT448-Fall 2017 IT448- Fall2017.
The Android Activity Lifecycle
CIS 470 Mobile App Development
Activities and Intents
Activities and Intents
CIS 470 Mobile App Development
Mobile Programmming Dr. Mohsin Ali Memon.
Activities and Fragments
Android Sensor Programming
Presentation transcript:

cosc 4730 Android GUI

Activity Lifecycle An activity has essentially four states: – If an activity in the foreground of the screen (at the top of the stack), it is active or running. – If an activity has lost focus but is still visible (that is, a new non-full-sized or transparent activity has focus on top of your activity), it is paused. A paused activity is completely alive (it maintains all state and member information and remains attached to the window manager), but can be killed by the system in extreme low memory situations. – If an activity is completely obscured by another activity, it is stopped. It still retains all state and member information, however, it is no longer visible to the user so its window is hidden and it will often be killed by the system when memory is needed elsewhere. – If an activity is paused or stopped, the system can drop the activity from memory by either asking it to finish, or simply killing its process. When it is displayed again to the user, it must be completely restarted and restored to its previous state.

Activities Android OS keeps track of all the Activity objects running by placing them on a Activity Stack. – When a new Activity starts, it is placed on top of the stack. – The previous Activity is now in background. If only partially obscured (say dialog box), only onpause() is called – onResume() called when the user can interact with it again if invisible to the user, then onpause() call, followed by onStop() – OnRestart() called, then onStart() when it becomes visible to the user – Or onDestroy() if the Activity is destroyed

GUI and layout To display anything on a android screen, it needs a layout. – This is a basic axiom of a android. An Exception can be a single widget displayed – All of this created in their xml (using eclipse or another xml editor for android). Note this can be done completely in java, but it is very tedious.

DroidDraw User Interface (UI) designer/editor for programming the Android Cell Phone Platform DroidDraw standalone executable available: (Mac OS X, Windows, Linux) – Remember, this a UI designer. It creates the xml file, then add them to the project.

Activity and xml The activity “inflates” the xml (the screen layout) and then display it to the screen. The activity is in java and setups all the rest of the pieces of the screen objects Event listeners. – It can also change/modify the screen objects.

Hello world example HelloWorld.java package edu.cs4755.HelloWorld; import android.app.Activity; import android.os.Bundle; public class HelloWorld extends Activity { /** Called when the activity is first created. public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } main.xml <LinearLayout xmlns:android=" m/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Hello World!" /> App displays:

xml Basic xml layout (one button displayed) <Button android:text="" android:layout_width="fill_parent" android:layout_height="fill_parent"> fill_parent uses all available space, wrap_content uses only as much space as is needed. id is what we need to find it with the java later. text would be the default text, in this case, nothing.

xml picture example <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" src access the drawable directory for a static picture, named phone. – Note this will only use as much of the screen as needed, because of wrap_content.

xml and widgets. Most widgets can be almost completely configured via xml instead of using java. This means the java can in many ways, be used only for the events, instead of dealing with display issues. Example: EditText – android:autoText boolean, use automatic spelling – android:capitalize boolean, Cap the first letter of the text entered – android:digits, accept only digits – android:singleLine, allow multi or single line input.

Layout "managers" Most of the time you need more then one widget. So you use a layout to control how the widgets are shown on the screen. LinearLayout is very simple <LinearLayout android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical"> Orientation controls placement of the next widget: – vertical: next line – horizontal: to the right of the previous widget Normally you use several layouts to control how everything is displayed.

multiple Layout example For presentation reasons lots of info was left off. <LinearLayout android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical">

Layout Settings Weight – If using Fill_parent, then each Widget can use Layout_Weight – This determines, which gets more space – Setting them all to 1, means they share the space equally. – Setting widget1 to 1 and widget2 to 2, means widget2 gets twice as much space as widget1

Layout Settings (2) Gravity – A nice way of saying alignment, which is flush on the left side of the screen – Layout_gravity: (Vertical) left (default) flush on the left side of the screen center_horizontal center right is flush on the right side of the screen. – Horizontal layout Center_vertical Center vertical, instead of on the "baseline" (bottom).

Layout Settings (3) Padding – how much in pixels space between the widget and the side of the screen/next widget – android:padding="15dp" is about 15 “pixels” all around – Also paddingLeft, paddingRight, paddingTop, and paddingBottom

Relative Layout More complex and widgets placed based on the previously placed widgets – Except the first one (no other widget yet) – layout_above, layout_below, layout_toLeftOf, layout_toRightOf – With the above, these can be used layout_alignTop, layout_alignBottom, layout_alignLeft, layout_alignRight, layout_alignBaseline Or placed relative to the container itself – layout_alignParentTop, layout_ParentBottom, layout_alignParentLeft, layout_parentRight, layout_centerHorizontal, layout_centerVertical, layout_CenterInParent Settings are placed in the Widgets

Relative Example <TextView android:text="Some Text " android:layout_alignParentBottom="true" > <Button android:text="alert" > NOTE : Button no + sign. + sign only needed for the id, when referencing it somewhere,

Other Layouts TableLayout works like html tables (with all the complications like spanning rows) – TableRow is used with it for row layouts Scrollwork is just like linearLayout, except you get a scrollbars as needed. absoluteLayout every is placed on the screen by setting the x and y pixels position

Screen Size and layouts. In the android directories, there is a res/ – drawable/ This deals with the screen density of pixels. – The configuration qualifiers you can use for density-specific resources are ldpi (low), mdpi (medium which is the baseline), hdpi (high), and xhdpi (extra high). For example, bitmaps for high-density screens should go in drawable-hdpi/.

Screen Size and layouts. Scaling: medium is the baseline – Small = mdpi*.75, high=mdpi*1.5 and xhigh=mdpi*2.0 Pixels: Small=36, medium=48, high=72, and xhigh=96 For density there are to more – nodpi Resources for all densities. These are density-independent resources. The system does not scale resources tagged with this qualifier, regardless of the current screen's density. – tvdpi Which is for TVs and google’s own doc’s say not to use it and use xhdpi instead. Except the new Nexus 7” tablet is a tvdpi device. – 1.33*mdpi or 100px image should be 133px

Screen Size and layouts. (2) – layout/ This is deals with the screen size. Layout/ is the default and the only one eclipse creates (or understands directly) We can have small (~ 426dp x 320dp), normal (470dp x 320 dp) which is the baseline, large (640dp x 480dp), and xlarge (960dp x 720dp) – We can also add land (landscape) and port (portrait) orientation. res/layout/my_layout.xml // layout for normal screen size ("default") res/layout-small/my_layout.xml // layout for small screen size res/layout-large/my_layout.xml // layout for large screen size res/layout-xlarge/my_layout.xml // layout for extra large screen size res/layout-xlarge-land/my_layout.xml // layout for extra large in landscape orientation

Screen Size and layouts. (3) In v3.2 (api 13), the size groups are deprecated for a new method. This is the problem: 7” tablet is actually in the 5” phone group, which is the large group. – Provides a smallestWidth (independent of orientation) and Width (which is also takes into account orientation) – layout-sw dp and layout-w dp Where N is the denisty of pixels.

Screen Size and layouts. (4) Typical configuration: – 320dp: a typical phone screen (240x320 ldpi, 320x480 mdpi, 480x800 hdpi, etc). – 480dp: a tweener tablet like the Streak (480x800 mdpi). – 600dp: a 7” tablet (600x1024 mdpi). – 720dp: a 10” tablet (720x1280 mdpi, 800x1280 mdpi, etc). Smallest width (no orientation) res/layout/main_activity.xml # For handsets (smaller than 600dp available width) res/layout-sw600dp/main_activity.xml # For 7” tablets (600dp wide and bigger) res/layout-sw720dp/main_activity.xml # For 10” tablets (720dp wide and bigger) Using just width and taking orientation into account res/layout/main_activity.xml # For handsets (smaller than 600dp available width) res/layout-w600dp/main_activity.xml # Multi-pane (any screen with 600dp available width or more) More information: There are two examples ScreenTest1.zip and ScreenTest2.zip to play with.

Widgets android.widget – The widget package contains (mostly visual) UI elements to use on your Application screen. Includes the layouts as well. – To create your own widgets, extend or subclass View. package: android.View Examples: – TextView, EditText, ProgressBar and SeekBar, Button, RaidoButton, CheckButton, ImageView, and Spinner This will cover only the basics, since every widget has many attributes. – Listeners will be listed.

TextView Displays text to the user and optionally allows them to edit it. – A TextView is a complete text editor, however the basic class is configured to not allow editing see EditText for a subclass that configures the text view for editing.

Interacting with the widgets HelloWorld.java package edu.cs4755.HelloWorld; import android.app.Activity; import android.os.Bundle; import android.widget.TextView; public class HelloWorld extends Activity { /** Called when the activity is first created. public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); TextView myView; myView = (TextView) findViewById( R.id.textview); myView.setText("Hello World 2!"); } main.xml <LinearLayout xmlns:android=" m/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Hello World!“ /> create a variable and use the id to find it

EditText EditText inherits from TextView – This is a method to get input. Has several subclasses, autocompeteTextView and ExtractEditText For a listener, implement the TextWatcher – and use EditText.addTextChangedLister( TextWatcher) – Override three methods void afterTextChanged(Editable s) – This method is called to notify you that, somewhere within s, the text has been changed. void beforeTextChanged(CharSequence s, int start, int count, int after) – This method is called to notify you that, within s, the count characters beginning at start are about to be replaced by new text with length after. void onTextChanged(CharSequence s, int start, int before, int count) – This method is called to notify you that, within s, the count characters beginning at start have just replaced old text that had length before.

Toast A toast is a view containing a quick little message for the user – When the view is shown to the user, appears as a floating view over the application. It will never receive – Also very handy for debugging. Example: – Toast.makeText(getApplicationContext(), “Hi!", Toast.LENGTH_SHORT).show(); Toast.LENGTH_SHORT or Toast.LENGTH_LONG is how long the message will show on the screen.

Button inherits from TextView represents a push-button widget implement Button.OnClickListener to listener for the push/click. – button.setOnClickListener(View.OnClickListener) – Override void onClick(View v) – Called when a view has been clicked.

RadioButton Inherits from CompoundButton (which inherits from Button) – RadioButtons are normally used together in a RadioGroup – RadioGroup is used to create multiple-exclusion scope for a set of radio buttons Also a Layout, which uses the same attributes as LinearLayout

RadioGroup Listener for RadioGroup – implement RadioGroup.OnCheckedChangeListener radioGroup.setOnCheckedChangeListener( ) – Override void onCheckedChanged(RadioGroup group, int checkedId) Called when the checked radio button has changed. CheckedId is RadioButton that was checked. clearCheck() clear the selection check(int id) sets a selection for the id – example id like R.id.RadioButton02

CheckBox A checkbox is a specific type of two-states button – can be either checked or unchecked – if (checkBox.isChecked()) { checkBox.setChecked(false); } – Listener implement CompoundButton.OnCheckedChangeListener CheckBox.setOnCheckedChangeListener(CompoundButton.O nCheckedChangeListener listener) – Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)

ToggleButton Like a checkbox or radio button Displays checked/unchecked states as a button with a "light" indicator and by default accompanied with the text "ON" or "OFF". – Two states: On and Off On shows a green button (default behavior) Off shows a grayed out button (default behavior)

ImageView To set a static image, this can be setup in xml using – Where phone is the png image in the drawable directory of the project. A bitmap can be setup using SetImageBitmap(Bitmap) method Drawable getDrawable() method gives you access to the image, where you can use the draw(Canvas ) method to change/draw on the image.

Graphics: Bitmap and Canvas android.graphics package – A simple way to some animation or “drawing on the screen” is to use a “blank” ImageView ImageView eImage = (ImageView) findViewById(R.id.eImage); Bitmap eBitmap= eBitmap = Bitmap.createBitmap(x, y, Bitmap.Config.ARGB_8888); Canvas eCanvas = new Canvas(eBitmap); //eCanvas has the graphics draw tools to write on the bitmap eCanvas.drawColor(Color.WHITE); //white screen Paint black = new Paint(Color.BLACK); //black paintbrush eCanvas.drawRect(0,0,x, y, black); eImage.setImageBitmap(eBitmap); eImage.invalidate(); //redraw the ImageView with new picture.

ImageButton inherits from ImageView In xml can set the images <item android:state_pressed="true" /> <item android:state_focused="true" /> /> Uses the listener like the button. View.onClickListener

Progress Bar A ProgressBar is like a gauge. – The bar can look in one of 4 ways, set in the style tag – android:progressBarStyle This is a medium circular progress bar – android:progressBarStyleHorizontal This is a horizontal progress bar. – android:progressBarStyleLarge This is a large circular progress bar. – android:progressBarStyleSmall This is a large circular progress bar. – The format looks like this: style="?android:attr/progressBarStyleHorizontal">

Progress Bar (2) SetMax(int m) uses to set the bar from 0.. m – Need to call this when it is setup in java – No setmin, zero is always the min. setProgress(int p) sets to a specific progress p int getProgress() returns the current level incrementProgressBy(int d) increments the progress by d.

SeekBar SeekBar is inherits ProgressBar and is touchable/ interactive. Otherwise it is the same as ProgressBar – Add a listener SeekBar.OnSeekBarChangeListener seekBar.onClickListener to add the listener – Must override 3 methods – public void onStartTrackingTouch (SeekBar seekBar) Use of a touch gesture – public void onStopTrackingTouch (SeekBar seekBar) touch gesture ended – public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) The seekBar has changed and it's progress fromUser is true if a user changed it

ArrayAdapter When we lists some type of "list" displayed, it uses an ArrayAdapter, which also needs a simple layout provided by android (don't need to create this layouts, unless you want to) – andriod.R.layout.X for the layouts. CN/reference/android/R.layout.html for the full list. – This can be override to make very fancy views, with say icons and text, clickable ratings and text, etc…

Spinner A spinner needs "items" to fill the drop down box. This is done using an ArrayAdapter – Using a string[] items, we can – ArrayAdapter adapter = new ArrayAdapter (this,android.R.layout.simple_spinne r_item, items); – adapter.setDropDownViewResource(android.R.layout.simp le_spinner_dropdown_item); – Then use setAdapter(adapter); //fills the list – Add listener, setOnItemSelectedListener(this) implement AdapterView.OnItemSelectedListener – public void onItemSelected(AdapterView parent, View view, int position, long id) – public void onNothingSelected(AdapterView parent)

Spinner (2) If instead, use an xml file with values – res/values/ – Stuff Stuff2 Change Adapter line to – ArrayAdapter adapter = ArrayAdapter.createFromResource( this, R.array.spinnerstuff, android.R.layout.simple_spinner_item);

DatePickerDialog DatePicker is a builtin dialog to pick a the date – TimePickerDialog picks the time – Also a ColorPickerDialog in the GraphicsActivity

DatePickerDialog (2) Calling the Dialog – constructor DatePickerDialog(Context context, DatePickerDialog.OnDateSetListener callBack, int year, int monthOfYear, int dayOfMonth) – Example: Calendar dateAndTime = Calendar.getInstance(); new DatePickerDialog(FormExample.this, d, //d is the listener dateAndTime.get(Calendar.YEAR), dateAndTime.get(Calendar.MONTH), dateAndTime.get(Calendar.DAY_OF_MONTH) ).show();

DatePickerDialog (2) listener: – in previous example assumed a declared listener, – if implemented, change d to this. declared listener d = new DatePickerDialog.OnDateSetListener() { public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { dateAndTime.set(Calendar.YEAR, year); dateAndTime.set(Calendar.MONTH, monthOfYear); dateAndTime.set(Calendar.DAY_OF_MONTH, dayOfMonth); } };

Dialog To create your own dialog, you first need a R.layout.name for it. So create an xml file for it dialog = new Dialog(this) dialog.setContentView(R.layout.name); dialog.setTitle("Whatever"); – Deal with any widgets in the dialog as well To show the dialog – dialog.show(); To remove it – dialog.dismiss();

Threads and widgets Only the original thread that created a view hierarchy can touch its view. – So you can't change widgets on threads you create! – To get around the problem, you need a handler specially a message handler. import android.os.Handler; import android.os.Message; private Handler handler = new Handler() public void handleMessage(Message msg) { if (msg.what == 0) { tvok.setText("Process done"); //Change the dialog textview. } }; // in the thread, (assuming handler is accessible to it) you can then send a message with handler.sendEmptyMessage(0); //where 0 is a message

Rotation To stop the auto rotation edit the AndroidManifest.xml In the <activity section android:screenOrientation= – portrait – landscape – Sensor (use accelerometers) appears to disable keyboard trigger events for slide keyboards This is per activity, so if you have more then 1 activity, it each can have their own orientation.

AndroidManifest.xml <manifest xmlns:android=" package="com.cosc4755.TCPclient" android:versionCode="1" android:versionName="1.0"> <activity android:name=".TCPclient" android:screenOrientation="portrait"

Launching a new Activity Using startActivity(), which takes a single parameter, an Intent – The new Activity will be placed on top of the Activity stack. – Example: startActivity(new Intent(getApplicationContext(), Next.class)); – To pass data to the activity, use putExtra with the Intent Intent myIntent = new Intent (getApplicationContext(), Next.class); myIntent.putExtra("StringData", "stuff"); myIntent.putExtra("BooleanData", true); startActivity(myIntent); To retrieve the data stored in a Bundle Object keys are prefixed by the package name, like edu.cs4730.ActivityDemo. StringData – Intent intent = getIntent(); – String data = intent.getStringExtra("edu.cs4730.ActivityDemo.StringData");

Launching a new Activity (2) AndroidManifest.xml file – Each new Activity must be registered in your manifest file – Inside the section You can also add intent-filter as well if you want specify different types of intents that can launch this Activity

Launching Other Activities You can launch Activities that don't belong to you application – Uri number = Uri.parse(tel: ); – Intent dial = new Intent(Intent.ACTION_DIAL, number); – startActivity(dial); – More intents android and 3 rd party can be found here app-intents.html

Services and Broadcast Receivers As you will see in android sms lecture, an Activity can be launched by a using Receivers – With sms, when a new sms message was receive the activity was launched to deal with the message. – The activity can be invisible to the users as it was with sms demo or launch as activity screen.

Notification status bar The notification system can also be used to launch a Activity (with user action). – Uses the Intent method again, to choose which Activity in your application is to launched. – See the Status Notification lecture for more details.

Get a result from an Activity You can use startActivityForResult(intent, int Request_code) to have an activity return information to call the calling activity. – Request is a integer number. You should attempt to kept the request code to each different activity unique but not required. – You then listen for results via the void onActivityResult(int requestCode, int resultCode, Intent data){ } – The requestCode is use to figure out which Activity has returned. ResultCode will be RESULT_CANCELED, if the activity didn't return anything or crashed.

Returning a result Using a intent and finish() the activity can return a result Intent myIntent = new Intent (getApplicationContext(), null); myIntent.putExtra("StringData", "stuff"); myIntent.putExtra("BooleanData", true); setResult(RESULT_OK, myIntent); – setResult( int resultCode, Intent Data) finish();

Closing activities There are a number of a ways for an Activity to close. – The primary method for an Activity to close is to call finish() This notifies the OS that this Activity is done (but not necessary the application If an activity called another and wants to be removed from the stack, it should call finish()

Closing activities (2) If you launched an Activity with startActivityForResult() and you want to end it, finishActivity(requestCode) will finish any activity with that requestCode

More? Android has a number of methods and call backs from activities and child activities – see the developers guide in the class android.app.activity to see more. And there are subclasses of activity as well – AccountAuthenticatorActivity Base class for implementing an Activity that is used to help implement an AbstractAccountAuthenticator. – ActivityGroup A screen that contains and runs multiple embedded activities. – AliasActivity Stub activity that launches another activity (and then finishes itself) based on information in its component's manifest meta-data. – ExpandableListActivity An activity that displays an expandable list of items by binding to a data source implementing the ExpandableListAdapter, and exposes event handlers when the user selects an item. – ListActivity An activity that displays a list of items by binding to a data source such as an array or Cursor, and exposes event handlers when the user selects an item. Known Indirect Subclasses LauncherActivity, PreferenceActivity, TabActivity

References See the FormExampleA.zip on the handout pages for source code. For a full list of xml and methods, see the developer guide, because I skipped a lot of information – Some information was also taken from the text Beginning Android 2, Apress, Mark L. Murphy, 2010

Q A &