Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 121

What’s Android

Android Phones

Sony X10

HTC G1 Samsung i7500 HTC Hero Motorola Cliq

HTC Magic HTC Tattoo


Motorola Droid
Samsung Moment 2
Smartphone Platform

• With the iPhone being the first to the


marketplace it sets the configuration of the
Smartphone Platform
– 3G/4G connectivity
– Wi-Fi connectivity
– Bluetooth connectivity
– accelerometer w/compass
– ambient light sensor
– proximity sensor
– GPS
– gyroscope
What is Android?

• Developed by Google
• Software stack for mobile devices that includes an
operating system, middleware and key
applications.
• Open Source (but not too open)
• Reuse and Replacement of components
• Linux Kernel

Includes a Java API for developing applications

Modern os , controlled and governed by Google
What is Android?

• A software stack for mobile devices that includes


– An operating system
– Middleware
– Key Applications
• Uses Linux to provide core system services
– Security
– Memory management
– Process management
– Power management
– Hardware drivers
Android vs. iPhone

Java vs. Objective-C


Direct install vs. Marketplace vs. App Store


Open source?
Mobile Devices

• It’s obvious that mobile device may take the


place of PC in future
• OS plays a vital part

Pr E A
D m Mi
oc
e be
dd p
es dd
le
vi wa p
so ed
ce re
r OS s

7
Brief History
• 2005
– Google acquires startup Android Inc. to start Android platform
– Work on Dalvik VM begins
• 2007
– Open Handset Alliance announced
– Early look at SDK
• 2008
– Google sponsors 1st  Android Developer Challenge
– T-Mobile G1 announced
– SDK 1.0 released
– Android released open source (Apache License)
– Android Dev Phone 1 released

Pro Android by Hashimi & Komatineni (2009) 8


Brief History cont.
• 2009
– SDK 1.5 (Cupcake)
• New soft keyboard with “autocomplete” feature
– SDK 1.6 (Donut)
• Support Wide VGA
– SDK 2.0/2.0.1/2.1 (Eclair)
• Revamped UI, browser
• 2010
– Nexus One released to the public
– SDK 2.2 (Froyo)
• Flash support, tethering
– SDK 2.3 (Gingerbread)
• UI update, system-wide copy-paste

9
Brief History cont.

• 2011
– SDK 3.0 (Honeycomb) for tablets only
• New UI for tablets, support multi-core processors
– SDK 3.1 and 3.2
• Hardware support and UI improvements
– SDK 4.0 (Ice Cream Sandwich)
• For Q4, combination of Gingerbread and Honeycomb

10
Android Features #1

• Application framework enabling reuse and


replacement of components
• Optimized Java virtual machine: Dalvik
• Optimized Graphics Processing, supporting 2D
and 3D graphics(OpenGL ES 1.0 )
• Integrated open source web browser: WebKit
• SQLite for structured data storage

11
Android Features #2

• Multimedia capability, supporting varieties


of audio, video and still image formats
• GSM Telephony
Hardware
• Bluetooth, EDGE, 3G and Wi-Fi support dependent
• Camera, GPS, compass, accelerometer
and other sensors support
• Rich development environment, including an
emulator, debugging tools, memory probe
tools, log tools and powerful eclipse plugins
12
Android makes mobile Java easier

Well, sort of…


Android version
Android Version
Android Version
Android Version
Android Version
Android architecture
Linux Kernel

• Note that Android based on a Linux kernel not a


Linux OS
• Supplies Security, Memory management, Process
management, Network stack and Driver model
• Acts as an abstraction layer between the
hardware and the rest of the software stack

21
Libraries

• Run in system background


• Using C/C++ Language
• 4 types of Libraries
– Bionic Libc, system C libraries
– Function Libraries, supporting multimedia, web
browser, SQLite...
– Native Servers
– Hardware
Abstraction Libraries

22
Core Libraries
• System C library, the standard C system library, tuned for embedded Linux-
based devices
• Media Libraries, support playback and recording of many popular audio
and video formats, as well as image files, including MPEG4, H.264, MP3,
AAC, AMR, JPG, and PNG
• Surface Manager, manages access to the display subsystem and seamlessly
composites 2D and 3D graphic layers from multiple applications
• WebKit, a modern web browser engine which powers both the Android
browser and an embeddable web view
• SGL, the underlying 2D graphics engine
• 3D libraries, an implementation based on OpenGL ES 1.0 APIs
• FreeType , bitmap and vector font rendering
• SQLite , a powerful and lightweight relational database engine

23
Andoid Runtime

• The core of Android platform


• Dalvik Virtual Machine
– Register-based
– Executes files in the Dalvik
Executable (.dex) format
• Java core Libraries
– Provides most of the functionality of the Java
programming language.

24
Android Runtime (cont.)

• The functions of Java core libraries rely on the


Dalvik VM and the underlying Linux kernel
• Multiple Dalvik VMs may run at the same time
• Every Android application runs in its own
process, with its own instance of the Dalvik
virtual machine
– The "dx" tool in Android SDK can transform
compiled JAVA class into the .dex format

25
Dalvik Virtual Machine

• Android custom implementation virtual machine


– Provides application portability and runtime consistency
– Runs optimized file format (.dex) and Dalvik bytecode
– Java .class / .jar files converted to .dex at build time
• Designed for embedded environment
– Supports multiple virtual machine processes per device
– Highly CPU-optimized bytecode interpreter
– Efficiently Using runtime memory
• Core Libraries
– Core APIs for Java language provide a powerful, yet simple and
familiar development platform

26
DVM vs. JVM

• DVM
– Google
– Dalvik executable
– Only supports a subset of standard Java Library
• JVM
– Sun
– Java bytecode
• Some worries that Java world may be divided into
different communities, each has its own Java standard

27
Application Framework

• Simplify the reuse of components


– Applications can publish their capabilities and any other
application may then make use of those capabilities
• Applications is a set of services and systems, include
– Views system, content providers, resources manager and
so on

28
Application Framework (cont.)

• Activity Manager, manages the lifecycle of applications and


provides a common navigation backstack
• Notification Manager, enables all applications to display
custom alerts in the status bar
• Resource Manager, providing access to non-code resources
such as localized strings, graphics, and layout files
• Content Providers, access data from other applications
(such as Contacts), or to share their own data
• Views, used to build an application, including lists, grids,
text boxes, buttons, and even an embeddable web browser

29
Applications

• A set of core applications shipped with Android


platform
– an email client, SMS program, calendar, maps, browser,
contacts, and others
• All written in Java
• Our applications are in the same level as these
applications

30
Android Lifecycle
Activity Lifecycle

Activity = methods +
Layout + Dialogs

Layout = Views,
Buttons, etc.

App = many Activities

Task = stack of
Activities from one app

Also: Services,
Broadcast Receivers,
Content Providers
Android development

Java Source
Android
Manifest
Generated Java .dex Dalvik
Class Compiler File VM
Resource
XML
Android
Libraries
Producing an Android App
javac
Java code Byte code

dx
.java .class Dalvik exe

classes.dex aapt

Byte code <xml>

Other .class files AndroidManifest.xml .apk

<str>

Resources
Android applications are compiled to Dalvik
bytecode

Write
Write app
app in
in Java
Java
Compiled
Compiled in
in Java
Java

Transformed
Transformed to
to Dalvik
Dalvik bytecode
bytecode

Loaded
Loaded into
into Dalvik
Dalvik VM
VM

Linux OS
The Dalvik runtime is optimized for mobile
applications

Run multiple VMs efficiently

Each app has its own VM

Minimal memory footprint


Life Cycle – Android Vs IOS
Android programming components
Presents a visual user interface for one focused endeavor
the user can undertake.
Activities List of menu items a user can choose from or display
photographs along with their captions

Doesn’t have a visual user interface, instead runs in the


background
Services Play background music as the user attends to other matters

Receives and reacts to broadcast announcements


Broadcast Receivers An application can announce to “whoever is listening” that
a picture was taken.

Makes a specific set of the application’s data available to


Content Providers other applications.
An application uses a contact list component

A simple message passing framework. Using intents you


Intents can broadcast messages system-wide or to a target Activity
or Service.
Android software development
Setup Development Environment

• Software Development Kit (SDK)


• IDE – Eclipse
• Eclipse plug-in - ADT
• Android Emulator
• Debugger
Where to download ?
• Go to this website
http://developer.android.com/sdk/index.html
Extract the SDK Zip to Your Custom Location.
adt-bundle-windows-x86\eclipse\eclipse.exe
Set Project Work Space Location
Set SDK Location in Preferences
• Window->preferences->android->sdk location=“ set your sdk location”->OK

Open eclipse Window->Preferences, select Android


Setup the SDK location as the folder where you extracted the downloaded SDK
zip file
Setup SDK API

• Open Window->Android SDK


• Click Available Packages and then choose
proper APIs to install, the latest may be the best
Window->Android sdk manager->select
package->install
Android Emulator
Android Emulator or AVD

• Emulator is essential to testing app but is not a


substitute for a real device
• Emulators are called Android Virtual Devices
(AVDs)
• Android SDK and AVD Manager allows you to
create AVDs that target any Android API level
• AVD have configurable resolutions, RAM, SD
cards, skins, and other hardware

50
Setup Emulators

• Window->Android virtual device manager->new


Setup Emulators
Ready…

• Now you may


start the AVD
– Click start to
start the new
AVD
– First start-up
may take a very
long time

53
Android Emulator: 1.6 Device

54
Android Emulator: 2.2 Device

55
Android Emulator: 3.0 Device

56
Emulator Limitations
• No support for placing or receiving actual phone calls
– Simulate phone calls (placed and received) through the emulator
console
• No support for USB connections
• No support for camera/video capture (input)
• No support for device-attached headphones
• No support for determining connected state
• No support for determining battery charge level and AC charging
state
• No support for determining SD card insert/eject
• No support for Bluetooth
• No support for simulating the accelerometer
– Use OpenIntents’s Sensor Simulator

57
You may test app with other Android Emulator
also.
You may test app with other Android Emulator
also.
Android Debugging
Debugging
• Instead of using traditional System.out.println, use the Log class
– Imported with android.util.Log
– Multiple types of output (debug, warning, error, …)
– Log.d(<tag>,<string>)
• Can be read using logcat.
– Print out the whole log, which auto-updates
• adb logcat
– Erase log
• adb logcat –c
– Filter output via tags
• adb logcat <tag>:<msg type> *:S
• can have multiple <tag>:<msg type> filters
• <msg type> corresponds to debug, warning, error, etc.
• If use Log.d(), then <msg type> = D
Where We Monitor

• DDMS (Dalvik Debug Monitor Server)



Eclipse integrated Android debugger

Windows > Open Perspective > Other... > DDMS

Select device, select process

Debug, Update Heap, Update Threads

Allows inspection of threads, heap, allocation,
files, etc.

Also displays Logcat and allows for screenshots!
Dalvik Debug Monitor Server(DDMS)
Android Debugging
Debug More….

• Some application we cant test with emulator, example


hardware/device dependent application .

1.camera application
2.sensor application
3.GPS Application

At that time if any one bug , it closes of whole application(The


Application has to be stopped Unfortunately), we cant find
which line the bug is it, then how we solve that problem????
Introduce a bug
package com.example.helloandroid;

import android.app.Activity;
import android.os.Bundle;

public class HelloAndroid extends Activity {


    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Object o = null;
        o.toString();
        setContentView(R.layout.main);
  }
}

@2011 Mihail L. Sichitiu 66


Run it!

@2011 Mihail L. Sichitiu 67


How we find a bug in a project
• Use try catch block mechanism and print exception using any UI Alert

Solution:

import android.app.Activity;
import android.os.Bundle;

public class HelloAndroid extends Activity {


    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
    
Try{
super.onCreate(savedInstanceState);
        Object o = null;
        o.toString();
        setContentView(R.layout.main);
}
Catch(Exception E){
Toast.makeText(getApplicationContext(), “Exception: “+E.toString(), Toast.LENGTH_LONG).show();
}

  } In this case the particular section program only thrown exception,
} remaining parts working fine .
Android Project Inner Structure
file structure for applications

All source code here Java code for our activity

All non-code Generated Java code


resources Helps link resources to
Java code

Images Layout of the activity

Strings used in the


program

Android Manifest
@2011 Mihail L. Sichitiu 70
UI layouts are in Java and XML

setContentView(R.layout.hello_activity); //will load the XML UI file


Important Files
• src/HelloAndroid.java
– Activity which is started when app executes
• res/layout/main.xml
– Defines & lays out widgets for the activity
• res/values/strings.xml
– String constants used by app
• gen/R.java (Don’t touch!)
– Auto-generated file with identifiers from main.xml, strings.xml, and
elsewhere
• AndroidManifest.xml
– Declares all the app’s components
– Names libraries app needs to be linked against
– Identifies permissions the app expects to be granted

72
src/HelloAndroid.java

• Activity which is started when app executes

73
res/layout/main.xml

• Declares layouts & widgets for the activity

74
res/values/strings.xml

• String constants used by app

• Used for supporting Localization


– res/values-es/values/strings.xml to support Spanish
– res/values-fr/values/strings.xml to support French
– Etc.

75
Strings
• In res/values
– strings.xml
• Application wide available strings
• Promotes good software engineering
• UI components made in the UI editor should
have text defined in strings.xml

• Strings are just one kind of ‘Value’ there are


many others
gen/R.java

• Auto-generated file with identifiers from main.xml,


strings.xml, and elsewhere

Do not
modify!

77
R Class

• Auto-generated: you shouldn’t edit it


• Contains IDs of the project resources
• Enforces good software engineering
• Use findViewById and Resources object to get
access to the resources
– Ex. Button b = (Button)findViewById(R.id.button1)
– Ex. getResources().getString(R.string.hello));
AndroidManifest.xml

• Declares all the app’s components


• Names libraries app needs to be linked against
• Identifies permissions the app expects to be granted

79
Core Components-Activity #1
• Basically, An activity presents a visual user interface for
one focused endeavor the user can undertake
• An application might consist of just one activity or several,
each Activity is derived from android.app.Activity and should
be declared in AndroidManifest.xml file
• Each activity is given a default window to draw in, the
window may be full screen or smaller and on top of other
window
• The visual content of the window is provided by a hierarchy
of views — objects derived from the base View class
• Activity.setContentView() method is used to set a certain
hierarchy of view objects
80
Core Components-Activity #2
• Activities are activated by asynchronous messages called
intents
– An intent is an Intent object that holds the content of the message
– The action being requested or the URI of the data to act on
• The <intent-filter> label in AndroidManifest.xml file specifies
the Intent that can start the Activity

– declares the main activity, it will be started automatically when the


app starts
• An activity is launched (or given something new to do) by
passing an Intent object to Context.startActivity() or
Activity.startActivityForResult()
81
Android Element and Layout
Where to modify UI Layout
• Res->layout->activity_main.xml
Various Layouts

84
Elements and layouts
• Table Layout
– Like the HTML div tag
/* table.xml */
<?xml version=“1.0” encoding=“utf-8”?>
<TableLayout android:layout_width=“fill_parent”
android:layout_height=“fill_parent”
android:stretchColumns=“1”>
<TableRow>
<TextView android:layout_column=“1”
android:text=“Open...”
android:padding=“3dip” />
<TextView android:text=“Ctrl-O”
android:gravity=“right”
android:padding=“3dip” />
</TableRow>
</TableLayout>
Elements and layouts
• Grid View

/* grid.xml */
<?xml version=“1.0” encoding=“utf-8”?>
<GridView
android:id=“@+id/gridview”
android:layout_width=“fill_parent”
android:layout_height=“fill_parent”
android:columnWidth=“90dp”
android:numColumns=“auto_fit”
android:verticalSpacing=“10dp”
android:horizontalSpacing=“10dp”
android:stretchMode=“columnWidth”
android:gravity=“center”
/>
Elements and layouts
• Grid View

/* GridExample.java */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.grid);

GridView gridview = (GridView) findViewById(R.id.gridview);


gridview.setAdapter(new AdapterForGridView(this));

gridview.setOnItemClickListener(
new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int pos, long id) {
Toast.makeText(
GridPrimer.this, "" + pos, Toast.LENGTH_SHORT).show();
}});
}
Elements and layouts
• Grid View

/* AdapterForGridView.java */
public class AdapterForGridView extends BaseAdapter {
private Context mContext;
public AdapterForGridView(Context c) { mContext = c; }
public int getCount() { return mThumbIDs.length; }
public Object getItem(int position) { return null;}
public long getItemId(int position) { return 0; }

// bad getView implementation


public View getView(int pos, View convertView, ViewGroup parent) {
ImageView imageView = new ImageView(mContext);
imageView.setImageResource(mThumbIDs[pos]);
return imageView;
}
private Integer[] mThumbIDs =
{ R.drawable.img1, R.drawable.img2 /*...*/ };
}
Elements and layouts
• Tab Layout
/* tab.xml */
<?xml version=“1.0” encoding=“utf-8”?>
<TabHost android:id=“@android:id/tabhost”
android:layout_width=“fill_parent”
android:layout_height=“fill_parent”>
<LinearLayout android:orientation=“vertical”
android:layout_width=“fill_parent”
android:layout_height=“fill_parent”>
<TabWidget android:id=“@android:id/tabs”
android:layout_width=“fill_parent”
android:layout_height=“wrap_content”/>
<FrameLayout
android:layout_width=“fill_parent”
android:layout_height=“fill_parent”/>
</LinearLayout>
</TabHost>
Elements and layouts
• Tab Layout
/* selector1.xml */
<?xml version=“1.0” encoding=“utf-8”?>
<selector xmlns:android=“http://schemas.android.com/apk/res/android”>
<!– Tab is selected -->
<item android:drawable=“@drawable/ic_tab_1_selected”
android:state_selected=“true” />
<!– Tab not selected -->
<item android:drawable=“@drawable/ic_tab_1_not_selected” />
</selector>

/* selector2.xml */

/* selector3.xml */
Elements and layouts
• Tab Layout
/* Tab1.java */
public class Tab1 extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

TextView textview = new TextView(this);


textview.setText(“This is the Artists tab”);
setContentView(textview);
}
}

/* Tab2.java */

/* Tab3.java */
Elements and layouts
• Tab Layout
/* TabExample.java */
public class TabExample extends TabActivity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tab);
TabHost tabHost = getTabHost();
//--- tab 1 ---
Intent intent = new Intent().setClass(this, Tab1.class);
TabHost.TabSpec spec = tabHost.newTabSpec(“tab1”).setIndicator(
“Artists”, getResources().getDrawable(R.drawable.selector1))
.setContent(intent);
tabHost.addTab(spec);
//--- tab 1 ---
tabHost.setCurrentTab(2);
}
Elements and layouts
• List View
/* list_item.xml */
<?xml version=“1.0” encoding=“utf-8”?>
<TextView
android:layout_width=“fill_parent”
android:layout_height=“fill_parent”
android:padding=“10dp”
android:textSize=“16sp” />
Elements and layouts
• List View
/* ListViewExample.java */
public class ListViewExample extends ListActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(this,
R.layout.list_item, COUNTRIES));
ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
    public void onItemClick(AdapterView<?> parent, View view,
      int position, long id) {
      Toast.makeText(getApplicationContext(),
((TextView) view).getText(), Toast.LENGTH_SHORT).show();
}});
}
Elements and layouts
• Button
• ImageButton
• EditText
• CheckBox
• RadioButton
• ToggleButton
• RatingBar
Elements and layouts
• DatePicker
• TimePicker
• Spinner
• AutoComplete
• Gallery
• MapView
• WebView
Menus
• Options Menu: MENU button, tied to an Activity
• Context Menu: View LongPress
• Submenu
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0, MENU_ADD, 0, “Add”)
.setIcon(R.drawable.icon);
menu.add(0, MENU_WALLPAPER, 0, “Wallpaper”);
return super.onCreateOptionsMenu(menu);
}
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case MENU_ADD: //... ; return true;
case MENU_WALLPAPER: //... ; return true;
default: return false;
}
}
Apps | intent
• Allows communication between components
– Message passing
– Bundle

Intent intent = new Intent(CurrentActivity.this, OtherActivity.class);


startActivity(intent);
Apps | intent
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Button listener
Button btnStart = (Button) findViewById(R.id.btn_start);
btnStart.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent intent =
new Intent(CurrentActivity.this, OtherActivity.class);
startActivity(intent);
}
});
}
Android UI Alerts
Apps | notifications
• Toast
• AlertDialog
• Notification

Toast.makeText(this, “Notification text”, Toast.LENGTH_SHORT).show();


Toast
•  Toast is a notification message that pop up, display a certain
amount of time, and automtaically fades in and out, most
people just use it for debugging purpose.

Code:
Toast.makeText(getApplication
Context(), "Button is clicked",
Toast.LENGTH_LONG).show();
AlertDialog
AlertDialog
• AlertDialog alertDialog = new AlertDialog.Builder(
•                         AlertDialogActivity.this).create();
•  
•         // Setting Dialog Title
•         alertDialog.setTitle("Alert Dialog");
•  
•         // Setting Dialog Message
•         alertDialog.setMessage("Welcome to AndroidHive.info");
•  
•         // Setting Icon to Dialog
•         alertDialog.setIcon(R.drawable.tick);
•  
•         // Setting OK Button
•         alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
•                 public void onClick(DialogInterface dialog, int which) {
•                 // Write your code here to execute after dialog closed
•                 Toast.makeText(getApplicationContext(), "You clicked on OK", Toast.LENGTH_SHORT).show();
•                 }
•         });
•  
•         // Showing Alert Message
•         alertDialog.show();
Android Example
Create a new Android Project

• File->New-
>Android project
– Project name
– Build Target
– Application
name
– Package name
– Create Activity

106
Hello World Project

• src: source folder


• gen: SDK generated file
• android 2.2: reference lib
• assets: binary resources
• res: resource files and
resource description files
• AndroidManifest.xml:
application description file
• default.properties: project
properties file

107
Hello World Tutorial
Hello World
Add the following lines marked by “// <-----”
Hello World Tutorial
Hello World
Run > Run > Android Application
Say Hello World

• modify HelloWorld.java

110
Run Hello World

• Select HelloWorld Project, Run->Run as->Android


Application
• ADT will start a proper AVD and run HelloWorld app on it

111
Behind HelloWorld #1
• R.java, generated by Android SDK, represents all the resources of the
app. resources are all in res folder
• resources are pre-compiled into binary format
/* AUTO-GENERATED FILE. DO NOT MODIFY.
*
* This class was automatically generated by the
* aapt tool from the resource data it found. It
* should not be modified by hand.
*/
package sample.hello;
public final class R {
public static final class attr {
}
public static final class drawable {
public static final int icon=0x7f020000;
}
public static final class layout {
public static final int main=0x7f030000;
}
public static final class string {
public static final int app_name=0x7f040001;
public static final int hello=0x7f040000;
}
112
}
Behind HelloWorld #2

• res/layout , contains layout declarations of the app, in XML


format, UIs are built according to the layout file

Linear Layout
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android=http://schemas.android.com/apk/res/android
android:orientation="vertical"
TextView, display
android:layout_width="fill_parent"
android:layout_height="fill_parent"> static text
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello" />
</LinearLayout>

A reference to
String resource
‘hello’ 113
Behind HelloWorld #3

• res/values, contains string declarations or other


values(e.g.:colors) of the app
– string.xml, contains string resources
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello">Hello World, HelloWorld!</string>
<string name="app_name">HelloWorld</string>
</resources>

referenced in referenced in
res/layout/activity_main.xml AndroidManifest.xml

114
Behind HelloWorld #4

• res/drawable, contains all image resources


– folders may have suffixes, app will choose the most
suitable one, so do the other resources
– three folders: drawable-ldpi, drawable-hdpi, drawable-
mdpi, each contains an icon.png file
– app will choose the proper icon according to the device
DPI
– reference name:@drawable/icon
• other folders we may use in future
– menu, anim (animation), xml ( preference and searchable)

115
Behind HelloWorld #5

• AndroidManifest.xml describe the application


– declare app’s name, version, icon, permission, etc…
– declare the application's components: activity, service
,receiver or provider
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="sample.hello" android:versionCode="1" android:versionName="1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".HelloWorld" android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER”/>
</intent-filter>
</activity>
</application>
<uses-sdk android:minSdkVersion="8" />
</manifest>

116
HelloWorld Example 2
• Build up an app that you can input your greetings
and display your greetings
– Input: EditText
– Display: TextView
– Of course, we have to add an button
• Edit res/layout/activity_main.xml file to add these
components

117
Beyond HelloWorld #2
• modify HelloWorld.java
– firstly get the references declared in activity_main.xml

– then add event response for Button

118
Beyond HelloWorld #3

• Finished!
• Run->Run as->Android Application

• Quite easy, isn’t it?


119
References

• This tutorial is a brief overview of some major


concepts…Android is much richer and more
complex
• Developer’s Guide
– http://developer.android.com/guide/index.html

• API Reference
– http://developer.android.com/reference/packages.html
Thank You

You might also like