380 likes | 530 Views
First lecture: general introduction Touches many aspects of Android programming Quite a few times several concepts pop up at the same time Can’t explain everything that comes up in this lecture but… After next lectures everything that comes up today should have been explained “recipes” snags.
E N D
First lecture: general introduction • Touches many aspects of Android programming • Quite a few times several concepts pop up at the same time • Can’t explain everything that comes up in this lecture but… • After next lectures everything that comes up today should have been explained • “recipes” • snags
General purpose OS for handheld devices Handhelds: resource constrained • Processing power • Memory • Persistent storage
What is Android? Linux-based OS for managing processes, memory and devices Support for functionality common on handhelds: telephony, video, graphics, GPS, speech etc. through Java libraries Android SDK supports most of Java Standard Edition (SE) except the standard java UI frameworks Abstract Windowing Toolkit (AWT) and Swing. Instead: own UI framework that looks a lot like the java framework
Second layer: C/C++ (“native”) libraries for functionality like database access (SQLite) and access to display system (Surface Manager) 2D/3D System C library (libc) based on Berkeley Software Distribution, tuned to half the original size Android runtime: Dalvik Virtual Machine, a version of the Java VM optimized for space, performance and battery life Consequence: NO COFFEEDREGS!
Top layers: application framework and the actual applications
Fundamental Android concepts (1): the Nodes of the app • Activity • Usually represents single screen in the appand can contain one or more Views (UI components) – can be seen as a component of a program • Apps usually consist of several activities – can be seen as a Java program • Activities are a standard Java classes that extend the Activity class • Content provider (not treated – too much additional information needed) • Standard mechanism to share data among apps • By declaring a class to extend the abstract class ContentProvider and declaring a “provider” intent filter, you can expose data to other apps • Simple example app: TelephoneList • Service(not treated) • Process running in the background, comparable to Windows services
Fundamental Android concepts (2) • View • User interface element: basic building blocks of the user interface: label, textbox, buttons, layout managers, … • A Viewis a Java class with a well-defined interface of which we don’t know its implementation • Documentation of all Android-specific classes: http://developer.android.com/reference/packages.html • AndroidManifest.xml • Defines contents and behavior of the app • Package, version, (write) permissions • Lists the nodes (activities, services, providers)
Fundamental Android concepts (3) • Intent • Class that is used to give a generic definition of an intention to start execution of other tasks, e.g. launch another activity in the same or another app launch an app that displays a web page • Android uses the intent to select an activity to start • If you specify that you want to, e.g., display a web page Intent i = new Intent(Intent.ACTION_VIEW); i.setData(Uri.parse("http://www.tue.nl"); this.startActivity(i); // this: calling activity Android selects an app that will Start a browser to display TU/e site If more browsers are installed Android will ask which one to start • You can also specify explicitly which app should handle the request • Demo follows later (week 6)
Fundamental Android concepts (4) • Android Virtual Devices (AVD) (exercises) • Allow to execute the code on your PC without attaching a real handheld to your PC • Can be created in many different configurations: screen size, memory etc. • Exam: only AVD may be used, no real devices! • For those who have no Android device: tablets can be borrowed from BCF (Asus, if necessary Cherry tablets) • AVD emulates Advanced RISC Machine (ARM) • RISC: Reduced Instruction Set Computing: • simplicity of processor chip design • speed achieved by reduced set of instructions, results in “small” chip
Development: Eclipse with Android plug-in • In place of DrJava • Execute apps on real device or on AVD • Extensive debugging facilities both for AVD as for real device • Breakpoints • Step over • Step into • Run to line (go to line where cursor is placed) • Values of attributes, local variables • Call stack • Context sensitive help • Opening Android/Java reference (browser) • Inspect file system of AVD/real device with DDMS perspective • Make sure that your AVD works – ask help if needed!!! • Next slides: “tour” of an Android project and how to accomplish things in Eclipse until Activities are discussed
Create an Android project File->New->Android Application project - starts a wizard The wizard creates Hello World • A framework for your project • a basic framework for your Activity class • icons for your app • an XML file that specifies that the screen consists of a tittle bar, a layout and a label: the layout is a ViewGroup, a container that can contain other GUI elements all GUI elements inherit from the View class the outermost View is a ViewGroup, unless there is only one View • string and other resources • references to libraries needed
Hello World Create project with File->New->Android Application project Later more details about Activities
“Hello World” Structure of Eclipse project made with File->new->Android Application Project Important parts for us: src: source code Android convention: package name reflects organization (code is organized in packages) I mostly use nl.tue.win as prefix (following Google’s recommendation) gen: generated code assets: arbitrary folders/files bin: compiled code res: resources – icons, strings, colors, screen layouts,… AndroidManifest.xml: application structure
Hello.java source code package nl.tue.win.hello; import android.os.Bundle; import android.app.Activity; import android.view.Menu; public class Hello extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.hello); } @Override public booleanonCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.hello, menu); return true; } } No main()! Instead: onCreate(Bundle …) - Bundle discussed later R.layout.hello Layout file for the screen: res/layout/hello.xml Observations?
Hello.java (continued) • setContentView(R.layout.hello): • creates the objects defined by the XML file • sets the screen contents to the outermost Viewobject in the XML file • displays the screen • onCreateOptionsmenu: is called when GUI is created • the MenuInflater creates the classes for the menu from the xml file res/menu/hello.xml • menus are not treated in the lectures – not really complicated to work out how to use • Result of pressing the menu button or pressing the “menu” symbol (3 squares):
Creating the Graphical User Interface (later more detail) The GUI is built with elements called Views A simple control is already on the “canvas”: a label A label (TextView) is used to display a text to the user • Open hello.xml in de res/layout project folder in Graphical Layout tab • Righ-click the label in the canvas or in the outline window • Select “Edit Text” • The “Resource Chooser” shows that the string has name hello_world and has a value like “Hello world!” • The string is a “resource” that is referred to by an identifier
Creating the Graphical User Interface (continued) • Click “New String” • Enter a new value for the string, e.g., “Hello Class” • Enter a new name for the string, e.g., “helloclass” (don’t enter the quotes in either case!) • From these data, a string is added to R, a class that represents resources • R.string are string resources • Each resource is identified by an integer • The new string is available in your program by Resources r = this.getResources(); String s = r.getString(R.string.helloclass);
Resources Key role in Android architecture – Resource • file (e.g. icon or file that describes layout), e.g., hello.xml • Value (string, color), e.g. the string named hello or the color white: #ffffffff • Identified by an ID in an XML file in the res directory: strings in the directory res/values pictures in the directories res/drawable, res/drawable/hdpi etc. layouts in the directory res/layout • When a file is added/changed, the Eclipse plugin automatically adds to or updates the file R.java after the file is saved (but sometimes it takes a while). • R connects the ID in the XML file with an integer that identifies it to Android • Access to resources e.g. by this.findViewById(R.id.editText1) or r.getString(R.string.hello)from an activity as shown before
R.Java (incomplete - comments added): package tue.win.hello; public final class R { . //outer class R public static final class drawable { //inner class R.drawable. public static final intic_launcher=0x7f020000; // application icon: R.drawable.ic_launcher } public static final class id { public static final int editText1=0x7f050001;//R.id.editText1 public static final intrl_id=0x7f050000;//R.id.rl_id } public static final class layout { public static final int main=0x7f030000; // main.xml R.layout.main } public static final class string { //strings.xml public static final intapp_name=0x7f040001; public static final int hello=0x7f040002; //R.string.hello : "Hello World! " } } In R.java, each resource is thus identified by an integer R.<inner class>.<attribute> Access to resources in Java: get an instance r of the class Resources from getResources() Access a resouce with ID id with, e.g., r.getString(int id) or r.getColor(int id) Alternatively: this.findViewById(R.id.<ID>)
Properties of Views All controls in the palette inherit from the View class Right-click the TextView, shows many built-in properties like Layout width/height and text color “Other Properties” has a sub menu “Defined by TextView” (properties specific for a TextView) “Inherited from View” (properties that all classes inheriting from View have) For a label, usually, we only need properties like text color font background color text direction …
Help Documentation of the Android classes: • http://developer.android.com/reference/packages.html • Quality varies; sometimes incomplete • Search function: • if chosen from dropdown list: API reference • else: general search results page, often from http://developer.android.com/guide/components/index.html • Context sensitive help in Eclipse: after “.”: list of functions of class (F2 to fix the pop-up screen) – very useful!
XML • Important role in Android applications • Allows to define multiple layouts with less (Java) code: • define layouts for both screen orientations • handle different screen resolutions • handle different screen sizes e.g. prepare layouts for different screen sizes and resolutions select one in the code that fits best to the actual screen • Manifest • Support for multi-language (example in week 6) In general: DO NOT EDIT XML directly, use the IDE GUI tools instead!!! Please, no Groundhog day experience for me!
XML • We avoid direct use of XML (use graphical facilities of IDE or code instead); nevertheless a few examples: • From the file res/values/strings.xml <string name="hello_world">Hello World!</string> the string “Hello World!” is identified by the name hello_world • From the file res/layout/hello.xml the xml for the label <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/hello_world" /> • XML is converted to code on the device itself; can lead to errors that could have been picked up in the IDE by, e.g., syntax checks if we had coded this in Java
“Resources” view of the string we created ( in file res/values/strings.xml; open file to see default “Resources” view): Basically, this is an editor with which we can avoid using XML directly “Graphical layout” view of the string:
XML view of the layout <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=".Hello" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/hello_world" /> </RelativeLayout>> RelativeLayout: will place controls relative to parent (the layout) and to each other
The Manifest Describes properties of the app to Android: application structure, organizational properties, (write) permissions,…Tab page 1 – general – usually no need to edit, except Uses Sdk
Sometimes needed to set minimum SDK version, in particular for Gridlayout. New version of SDK puts Min SDK version to 8 and Gridlayout needs 14 • Current SDK also sets Target SDK version to 18 (for your real device, you may have to change this and install extra Android packages – will be explained in Monday’s exercises)
tab page 2: Application Structure Android creates an object of a class derived from the abstract class Application All activities in the app share this object Notice: app_name (banner) Icon (launcher screen icon) Intent Filter says activity Hello can be started as main is added to launcher screen
Extend the app with a text box (class EditText) – allows user to enter text (demo) Two ways: • With the Graphical Designer: Add the EditText by dragging it (“plain text”) from the palette (tab Text Fields) to the “canvas” – notice the relation of position with respect to parent/TextView Notice: no code is added! EditText shows up in the res/layout/main.xml file Using the Graphical Designer in general saves many lines of code Note: The name “canvas” is somewhat confusing as there is also a class Canvas; the canvas here is not a canvas on which one can draw! It is the canvas of the Graphical Designer only.
Add the text box with code Assign an id to the RelativeLayout(right-click in Outline and choose “Assign ID”, e.g. rl_id; save layout – we need to get hold of the instance via the id The RelativeLayout defines how its Views are laid out In the code: add attributes and add import statements (QuickFix or ctrl-shift-M) RelativeLayoutrl; EditTextet; In onCreate: rl= (RelativeLayout)this.findViewById(R.id.rl_id); // notice cast et = new EditText(this); rl.addView(et); Notice: this must be done after the call to setContentView, as the Views are instantiated during that call! Before the call, findViewById will return a RelativeLayout, but its value is null…
Activities • One screen (usually) and some functionality • When a new activity is started, Android puts the previously active one on a stack • Android builds up a stack of activities that are still “alive” but that don’t have the focus • Demo (Icons): what happens if we turn the screen? • When the screen is turned, Android kills all activities and restarts them • Likewise, when Android runs low on resources, it will also kill activities to free resources (harder to demonstrate) • Next slide: activity lifecycle. • New in Android: Fragments, which have more complicated life cycle. We decided to only discuss activities.
Activity life cycle • States: • Created • Started • Activity Running • Paused (partially visible) • Stopped (hidden) • When in the stopped state, • Android may kill the app • App process killed • Activity shut down • Methods shown are called by Android • when transitions occur
Activity life cycle When the activity starts for the first time, it comes to the foreground and receives user focus Android calls various methods depending on the state changes of the activity. When the Activity does not override these, the corresponding methods of super are called. The most important ones: • onCreate • Called when activity is first created. • Also called when activity is restarted after the Stopped state • Argument of the onCreate method: used to restore critical state information When called first time argument is null • When the activity was stopped before, information that was saved in the Bundle is available (state of Views is saved by super!): when stopped, not only the method onStop() but also the method onSaveInstanceState(Bundle state) is called to allowsaving state in a Bundle
Activity life cycle (continued) • onPause • Called when other activity comes in foreground. • If your app is, e.g., running a video you may want to pause the video. • One should also stop any action that consumes CPU cycles or uses other resources (e.g. the camera). • This is also the point to save unsaved changes (to a database or file) e.g. when the user is editing a document or an email (although the onStop method may be more appropriate). • onResume Called when activity comes to the foreground again so here you can, e.g., restart the video, reinitialize the camera, etc.
Activity life cycle (continued) • onStop • Called when the activity may be killed e.g., when the user receives a phone call or starts another app that hides the current one. • Activity should release most of the resources it is using. • CPU intensive work should be done here instead of in the onPause method, like saving data in a database. • Notice: the state of View objects (e.g. EditText) is retained in a Bundle and handled by the super class – hence the call super.onCreate • Wild guess: activities that use most memory (or other resources) are killed first… Demo (Icons): save and restore state Other ways to solve problem?