SlideShare ist ein Scribd-Unternehmen logo
1 von 68
Android Programming
Labs
Complied by: Shady Selim
Table of Contents
Module I.............................................................................................................................. 2
Getting Started.................................................................................................................. 2
Module II............................................................................................................................. 2
Activities, Fragments,....................................................................................................... 2
and Intents......................................................................................................................... 2
Module III............................................................................................................................ 2
Android User Interface..................................................................................................... 2
Module IV........................................................................................................................... 2
Sensors.............................................................................................................................. 2
Module V............................................................................................................................ 2
Bluetooth, NFC, Networks, and...................................................................................... 2
Wi-Fi.................................................................................................................................... 2
Module VI ........................................................................................................................... 2
I/O file ................................................................................................................................. 2
Module VII .......................................................................................................................... 2
Database ............................................................................................................................ 2
Module VIII ......................................................................................................................... 2
Networking......................................................................................................................... 2
Module IX........................................................................................................................... 2
Developing Android Services......................................................................................... 2
Module X............................................................................................................................ 2
Audio and Video................................................................................................................ 2
Module I
Getting Started
SETUP
Prepare your computer – Install SDK: Windows, Mac, Linux
We assumeyou have already installed the Java JDK and EclipseIDEin your
computer
• Java JDK is availableat:
http://www.oracle.com/technetwork/java/javase/downloads/index.html
• EclipseIDEfor Java EE Developers is availableat:
http://www.eclipse.org/downloads/
The next instructions aregiven to:
(a) User Wanting to Update their Older Android Workbench,
(b) FirstTime Users.
SETUP
(a) Users Wanting to Update an Older Android Workbench
If you are currently using the Android SDK, you justneed to update to the latest
tools or platformusing the already installed Android SDK and AVD Manager.
1. Click onthe SDK
Manager icon.
2. You will see a formsimilar
to the one onthe right.
3. Select the Packages you
want to installandwait
until theyare setupin
your machine.
SETUP
(b) First Time Users (Windows, Mac, Linux)
1. InstalltheappropriateSDK starter package fromthepage
http://developer.android.com/sdk/index.html
2. InstalltheADT Plugin for Eclipse
1. StartEclipse,then selectHelp > Install New Software....
2. ClickAdd button (top‐rightcorner)
3. In thenextdialog‐boxenter "ADT Plugin" for the Nameand thefollowing
URL for theLocation:https://dl‐ssl.google.com/android/eclipse/
4. ClickOK
5. Selectthecheckbox nextto DeveloperTools and click Next > Next
6. Acceptthelicenseagreements,then click Finish.
7. After theinstallation end you need to restartEclipse.
3. Add Android platforms and other components to yourSDK (seeprevious
option (a) )
Configuring the ADT Plugin
The next step is to modify your ADT preferences in Eclipseto pointto the
Android SDK directory:
1. Select Window > Preferences... to open the Preferences panel
(Mac OS X: Eclipse > Preferences).
1. Select Android from the left panel.
2. To set the box SDK Location that appears in the main panel,
click Browse... and locateyour downloaded SDK directory ( usually
c:/ProgramFiles (x86)/Android /android‐sdk )
3. Click Apply, then OK.
Done
Selecting an Android Virtual Device (AVD)
You should testyour applications on a real phone (or tablet).
However, the SDK allows you to create realistic virtual devices
on which your applications can betested.
Creating an Android Virtual Device (AVD)
An AVD allows you to simulated devices and SDKs.
To create a virtual unitfollowthe next steps:
1. Click onthe AVDManager
2. Click New. The Create New AVD dialog appears.
3. Type the name ofthe AVD, such as “18‐JellyBean"
4. Choose a target (suchas “Google APIs…API Level18”).
5. Indicate howmuchmemorythe simulator will use.
6. Tick option box “Snapshot” to loadfaster.
7. Indicate screensize (HVGA is sufficient ingeneral)
8. Optionallyspecifyanyadditional hardware components
(such as SD‐card, camera,…)
9. Click Create AVD.
Module II
Activities,
Fragments,
and Intents
LifeCycle App
EXAMPLE: LifeCycle app
The following application demonstrates the transitioning of a
simple activity through the Android’s sequence of Life‐Cycle states.
1. A Toast‐msgwill bedisplayed showing the currentevent’s name.
2. An EditText box is provided for the user to indicatea background color.
3. When the activity is paused theselected background color valueis saved to
a SharedPreferences container.
4. When the application is re‐executed the lastchoiceof background color
should be applied.
5. An EXIT button should be provideto terminate the app.
6. You areasked to observe the sequence of messages when the application:
1. Loads for the firsttime
2. Is paused after clicking HOME button
3. Is re‐executed from launch‐pad
4. Is terminated by pressing BACK and its own EXIT button
5. Re‐executed after a background color is set
Layout: atcivity_main.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/myScreen1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<EditText
android:id="@+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Pick background (red, green, blue, white)"
android:ems="10" >
<requestFocus />
</EditText>
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Exit" />
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=" spy box ‐ try clicking HOME and BACK" />
</LinearLayout>
33
LifeCycle App (1)
34
LifeCycle App (2)
package csu.matos.lifecycle;
import java.util.Locale;
. . . //other libraries omitted for brevity
public class MainActivity extends Activity {
//class variables
private Context context;
private int duration = Toast.LENGTH_SHORT;
//Matching GUI controls to Java objects
private Button btnExit;
private EditText txtColorSelected;
private TextView txtSpyBox;
private LinearLayout myScreen;
private String PREFNAME = "myPrefFile1";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//display the main screen
setContentView(R.layout.activity_main);
//wiring GUI controls and matching Java objects
txtColorSelected = (EditText)findViewById(R.id.editText1);
btnExit = (Button) findViewById(R.id.button1);
txtSpyBox = (TextView)findViewById(R.id.textView1);
myScreen = (LinearLayout)findViewById(R.id.myScreen1);
3)
//set GUI listeners, watchers,...
btnExit.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
//observe (text) changes made to EditText box (color selection)
txtColorSelected.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// nothing TODO, needed by interface
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// nothing TODO, needed by interface
}
@Override
public void afterTextChanged(Editable s) {
//set background to selected color
String chosenColor = s.toString().toLowerCase(Locale.US);
txtSpyBox.setText(chosenColor);
setBackgroundColor(chosenColor, myScreen);
}
}); 36
LifeCycle App (4)
//show the current state's name
context = getApplicationContext();
Toast.makeText(context, "onCreate", duration).show();
} //onCreate
@Override
protected void onDestroy() {
super.onDestroy();
Toast.makeText(context, "onDestroy", duration).show();
}
@Override
protected void onPause() {
super.onPause();
//save state data (background color) for future use
String chosenColor = txtSpyBox.getText().toString();
saveStateData(chosenColor);
Toast.makeText(context, "onPause", duration).show();
}
@Override
protected void onRestart() {
super.onRestart();
Toast.makeText(context, "onRestart", duration).show();
}
LifeCycle App (5)
@Override
protected void onResume() {
super.onResume();
Toast.makeText(context, "onResume", duration).show();
}
@Override
protected void onStart() {
super.onStart();
//if appropriate, change background color to chosen value
updateMeUsingSavedStateData();
Toast.makeText(context, "onStart", duration).show();
}
@Override
protected void onStop() {
super.onStop();
Toast.makeText(context, "onStop", duration).show();
}
LifeCycle App (6)
private void setBackgroundColor(String chosenColor, LinearLayout myScreen) {
//hex color codes: 0xAARRGGBB AA:transp, RR red, GG green, BB blue
if (chosenColor.contains("red"))
myScreen.setBackgroundColor(0xffff0000); //Color.RED
if (chosenColor.contains("green"))
myScreen.setBackgroundColor(0xff00ff00); //Color.GREEN
if (chosenColor.contains("blue"))
myScreen.setBackgroundColor(0xff0000ff); //Color.BLUE
if (chosenColor.contains("white"))
myScreen.setBackgroundColor(0xffffffff); //Color.BLUE
} //setBackgroundColor
private void saveStateData(String chosenColor) {
//this is a little <key,value> table permanently kept in memory
SharedPreferences myPrefContainer = getSharedPreferences(PREFNAME,
Activity.MODE_PRIVATE);
//pair <key,value> to be stored represents our 'important' data
SharedPreferences.Editor myPrefEditor = myPrefContainer.edit();
String key = "chosenBackgroundColor";
String value = txtSpyBox.getText().toString();
myPrefEditor.putString(key, value);
myPrefEditor.commit();
}//saveStateData
LifeCycle App (7)
private void updateMeUsingSavedStateData() {
// (in case it exists) use saved data telling backg color
SharedPreferences myPrefContainer =
getSharedPreferences(PREFNAME, Activity.MODE_PRIVATE);
String key = "chosenBackgroundColor";
String defaultValue = "white";
if (( myPrefContainer != null ) &&
myPrefContainer.contains(key)){
String color = myPrefContainer.getString(key, defaultValue);
setBackgroundColor(color, myScreen);
}
}//updateMeUsingSavedStateData
} //Activity
LifeCycle App (8)
LifeCycle App (9)
42
The app is re‐executed
LifeCycle App (10)
Saved stateinformation defining
background color is reusedby the
new app’s instance. Lifecyclebegins
on the onCreate state
User selects a green
background andclicks Exit.
When the appis pausedthe
user’s selectionis savedand
the app finallyterminates. 43
The app is re‐executed
LifeCycle App (11)
The app is re‐startedand becomes
visibleagain,showing all thestate
values previouslyset by theuser
(see the text boxes)
User selects a green
background andclicks the
HOME key. Whentheapp is
paused theuser’s selection is
saved,theapp is still active
but it is not visible.
Module III
Android User
Interface
Basic Widgets: Labels
<?xml version="1.0" encoding="utf‐8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/widget32"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/txt1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#ffffff00"
android:inputType="none"
android:text="@string/long_msg_1"
android:textSize="20sp" />
</LinearLayout>
Hint on Better Programming Style:
Add to the res/values/stringg.xml the entry
<string name=“long_msg_1">Line1of longmessagenLine2 of long msgn...nlastline</string>
EditText Caution
WARNING
This text field does not specify an
InputType or a hint
is justa warning requesting your help to improve
the working of a TextView. Add the clause
android:hint=“…some hint here…” and/or
android:InputType=“…choice…” where
choices are
a
Basic Widgets: Buttons
• A Button widget allows thesimulation of a clicking action on a GUI.
• Button is a subclass of TextView. Therefore formatting button’s face
is similar to the setting of a TextView.
<Button
android:id="@+id/
Basic Widgets: Images
• ImageView and ImageButton are two Android
widgets that allowembedding of images in your
applications.
• Analogue to TextView and Button controls
(respectively).
• Each widget takes an android:src or
android:background attribute (in an XML layout)
to specify what pictureto use.
• Pictures areusually stored in the res/drawable folder
(optionallya low,medium, and high definition
version of the same image could be stored to later be
used with differenttypes of screens)
=
"@string/click me"
Basic Widgets: Images
<LinearLayout
. . .
<ImageButton
android:id="@+id/myImageBtn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher" >
</ImageButton>
<ImageView
android:id="@+id/myImageView1"
android:layout_width="150dp"
android:layout_height="120dp"
android:scaleType "fitXY"
android:src="@drawable/flower1" >
</ImageView>
</LinearLayout>
This is a jpg,
gif, png,…file
Basic Widgets: Combining Images & Text
A common Button could display textand a
simpleimageas shown below
<LinearLayout
. . .
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:drawableLeft="@drawable/ic_happy_face"
android:gravity="left|center_vertical"
android:padding="15dp"
android:text= @string/click_me />
</LinearLayout>
Basic Widgets: Images
Icons are small images used to graphically representyour application and/or
parts of it. They may appear in different places of the device including:
• Home screen
• Launcher window.
• Options menu
• Action Bar
• Status bar
• Multi‐tab interface.
• Pop‐up dialog boxes
• List view
Detailed information at:
http://developer.android.com/guide/practices/ui_guidelines/icon_design.html
HINT
Several websites allowyou to convert your pictures to image files under a
variety of formats & sizes (.png, .jpg, .gif, etc). For instancetry:
http://www.prodraw.net/favicon/index.php
http://converticon.com/ 59
Basic Widgets: EditText
• The EditText (ortextBox) widgetis
an extension of TextView that
allowsuser’sinput.
• The control candisplay editable
text(usesHTML‐styles:bold, ... ).
• ImportantJavamethods are:
txtBox.setText(“someValue”)
and
txtBox.getText().toString()
Basic Widgets: EditText
• The EditText (ortextBox) widgetis
an extension of TextView that
allowsuser’sinput.
• ImportantJavaI/Omethods are:
txtBox.setText(“someValue”)
and
txtBox.getText().toString()
• The control candisplay editableor
HTML‐formatted textbymeansof
Html.fromHtml(text)
Basic Widgets: EditText
CAUTION: Deprecated Methods
• android:autoText
• android:capitalize
• android:digits
• android:singleLine
• android:password
• android:numeric
• android:phonenumber
Instead use the newer atttribute:
android:inputType=“…choices…”
where choices include
Basic Widgets: EditViews
Example
...
<EditText
android:id="@+id/txtUserName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textCapWords|textAutoCorrect"
Enter “teh” It will
be changed to: “the”
Each wordis
android:hint="@string/enter_your_first_and_last_name" capitalized
android:textSize="18sp" />
... Suggestion (greyout)
Example: Login Screen
In this examplewe will createand use a simplelogin screen holding a
label( TexView), a textBox (EditText), and a Button. A fragment of its
functionality isshown below.
Hint Capitals &
spelling
Setting
text
A brief
message box
"1
Example: Login Screen
Layout Design 1 of 2
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#886495ed"
android:orientation="vertical"
android:padding="2dp" >
<TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="1dp"
android:background="#ffffff00"
android:text="@string/ACME_Corp_Caption" />
<EditText
android:id="@+id/txtUserName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="1dp"
android:hint="@string/Enter_your_First_and_Last_name"
android:inputType="textCapWords|textAutoCorrect"
android:textSize="18sp" >
<requestFocus />
</EditText>
65
Example: Login Screen
Layout Design 2of 2
<Button
android:id="@+id/button1"
android:layout_width="82dp"
android:layout_height="wrap_content"
android:layout_marginTop="1dp"
android:text="@string/login" />
</LinearLayout>
Resource Captions: res/values/strings
<?xml version= 1.00" encoding="utf‐8"?>
<!‐‐ this is the res/values/strings.xml file ‐‐>
<resources>
<string name="app_name">GuiDemo</string>
<string name="action_settings">Settings</string>
<string name="login">login</string>
<string name="ACME_Corp_Caption">login</string>
<string name="Enter_your_First_and_Last_name">Enter your First and Last name</string>
</resources>
Example: Login Screen
Rendering the Layout
The images belowshowthe previouslydefined loginscreendisplayed bytwo
different devices running SDK2.3 (Gingerbread)andSDK4.3 (Ice Cream)
GingerBread SDK Ice Cream SDK 67
Example: Login Screen
MainActivity.java Class (1 of 2)
package csu.matos.g uidem o;
import ...
// "LOGIN" ‐ a gentle introduction to UI controls
public class MainActivi ty extend s Activity {
//class variables representing UI controls to be controlled from the program
TextView labelUserName;
EditText txtUserName;
Button btnBegin;
//variables used with the Toast message class
private Context context;
private int duration = Toast.LENG TH_SHO RT;
@Override
public void onCreate(Bu ndle savedIn stanc eState ) {
super.on Create (save dInsta nceSt ate);
//show the login screen
setContentView(R.layout.activity_main);
context = getApplicationContext();
Example: Login Screen
MainActivity.java Class (2 of 2)
//binding the UI's controls defined in "main.xml" to Java code
labelUserName = (TextView) findViewById(R.id.textView1);
txtUserName = (EditText) findViewById(R.id.txtUserName);
btnBegin = (Button) findViewById(R.id.button1);
//LISTENER: allowing the button widget to react to user interaction
btnBegin.setOnClickListener(ne w OnClickL istene r() {
@Override
public void onClick(Vie w v) {
String userName = txtUserName.getText().toString();
if (userName. compar eTo("M aria Macare na")== 0){
labelUserName.setText("OK, please wait...");
Toast.makeText(context,
"Bienvenido " + userName,
duration).show();
}
Toast.makeText(context,
userName + " is not a valid USER" ,
duration).show();
}
});// onClick
}//onCreate
}//class
Your turn!
Implement any/all of the following projects
Usingsimpletext boxes (EditText, TextView)
and buttons:
1. Currency calculator
2. Tip Calculator
3. Simple Flashlight
Common Layouts
FrameLayout
• FrameLayout is the simplesttype of GUI container.
• Useful as outermost container holding a window.
• Allows you to define how much of the screen (high,
width) is to be used.
• All its children elements arealigned to the top left corner
of the screen.;
The Linear Layout
1. Linear Layout
• The LinearLayout supports a filling strategy in which new elements are
stacked either in a horizontal or vertical fashion.
• If the layouthas a vertical orientation newrows areplaced one on top
of the other.
• A horizontal layoutuses a side‐by‐sidecolumn placement policy.
property can be set to:
"wrap content"
The Linear Layout
1. LinearLayout: Setting Attributes
Configuring a LinearLayout usually requires you to set the following attributes:
• orientation (vertical, horizontal)
• fill model (match_parent, wrap_contents)
• weight (0, 1, 2, …n )
• gravity (top, bottom, center,…)
• padding ( dp – dev. independentpixels)
• margin ( dp – dev. independentpixels)
The LinearLayout ‐ Orientation<LinearLayout
1.1 Attribute: Orientation
The android:orientation
horizontal
horizontal for columns, or
vertical for rows.
Use setOrientation() for
runtime changes.
v
e
r
t
i
c
a
l
xmlns:android="http://schemas.android.com/ap
k/res/android"
android:id="@+id/myLinearLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:padding="4dp" >
<TextView
android:id="@+id/labelUserName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#ffff0000"
android:text=" User Name "
android:textColor="#ffffffff"
android:textSize="16sp"
android:textStyle="bold" />
<EditText
android:id="@+id/ediName"
android:layout_width="wrap_content"
android:layout_height= wrap_content
android:text="Maria Macarena"
android:textSize="18sp" />
<Button
android:id="@+id/btnGo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Go"
android:textStyle="bold" />
</LinearLayout> 20
The LinearLayout – Fill Model
1.2 Fill Model
• Widgets have a "natural size“based on their included text (rubber band
effect).
• On occasions you may want your widget to have a specific spaceallocation
(height, width) even if no text is initially provided (as isthe caseof the empty
text box shown below).
natural sizes
empty screen space
The LinearLayout – Fill Model
1.2 Fill Model
All widgets insidea LinearLayoutmust include‘width’ and ‘height’ attributes.
android:layout_width
android:layout_height
Values used in defining height and width can be:
1. A specific dimension such as125dp (device independent pixels,a.k.a.dip )
2. wrap_content indicates the widget should justfill up its natural space.
3. match_parent (previously called ‘fill_parent’) indicates thewidget wants to
be as bigas the enclosing parent.
space
The LinearLayout – Fill Model
<?xml version="1.0" encoding="utf‐8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
1.2 Fill Model
125 dp
entire row
(320 dp on medium resol uti on scree ns)
android:id="@+id/myLinearLayout"
android:layout_width="match_parent "
android:layout_height="match_parent "
android:background="#ff0033cc"
android:orientation="vertical"
android:padding="4dp" >
<TextView
android:id="@+id/labelUserName"
android:layout_width="_parent"
android:layout_height="wrap_content
"
android:background="#ffff0066"
android:text="User Name"
android:textColor="#ff000000"
android:textSize="16sp"
android:textStyle="bold" />
<EditText
android:id="@+id/ediName"
android:layout_width="match_parent "
android:layout_height="wrap_content
"
android:textSize="18sp" />
<Button
android:id="@+id/btnGo"
android:layout_width="125dp"
android:layout_height="wrap_content
"
android:text="Go"
android:textStyle="bold" />
Row‐wise
Use all the row
Specific size: 125dp
.
</LinearLayout>
The LinearLayout – Weight
1.2 Weight
Indicates howmuch of the extra spacein the LinearLayout will beallocated to the
view. Use 0 if the view should not be stretched. The bigger the weight the larger
the extra given to that widget.
Example
The XML specification for this windowis
similar to the previous example.
The TextViewandButtoncontrols have
the additional property
android:layout_weight="1"
whereas the EditText control has
android:layout_weight="2"
Default value is 0
Takes: 2 /(1+1+2)
of the screen space
24
The LinearLayout – Gravity
1.3 Layout_Gravity
• It is used to indicatehowa control will align on the screen.
• By default, widgets are left‐ and top‐aligned.
• You may use the XML property
android:layout_gravity="…"
to set other possiblearrangements:
left, center, right, top, bottom, etc.
Button has
right
layout_gravity
The LinearLayout – Gravity
1.3 CAUTION: gravity vs. layout_gravity
The difference between:
android:gravity
indicates howto placean object within a container.In the example
the text is centered android:gravity="center"
android:layout_gravity
positions theview with respect to its
android:layout_gravity="center"
at
The LinearLayout – Padding
1.4 Padding
• The padding attribute specifies the widget’s internal margin (in dp units).
• The internal margin is theextra spacebetween the borders of the widget's
"cell"and the actual widget contents.
• Either use
• android:padding property
• or call method setPadding() runtime.
The LinearLayout – Padding
1.3 Padding and Marging
The LinearLayout – Padding
1.3 Internal Margins Using Padding
Example:
The EditText box has been changed to display 30dp of padding all around
<EditText
android:id="@+id/ediName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="18sp"
androi d:pa ddin g="3 0dp" />
...
The LinearLayout – Margin
1.4 (External) Margin
• Widgets –by default– are tightly packed next to each other.
• To increasespacebetween them use the android:layout_margin attribute
Increased inter‐widget space
<EditText
android:id="@+id/ediName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="18sp"
andro id:l ayou t_ma rgin ="6d p"
>
</EditText>
...
The Relative Layout
2. Relative Layout
The placement of widgets in a RelativeLayout is based on their positional
relationship to other widgets in the container and the parent container.
A
Example:
A is bythe parent’s top
C is below A, to its right
B is below A, to the left o
B C
The Relative Layout
2. Example: Relative Layout
Locationof the buttonis expressed
in reference to its relative position
with respect to the EditTextbox.
The Relative Layout
2. Referring to the container
Below there is a listof some positioning XMLboolean properties (=“true/false”)
useful for collocating a widgetbased on the location of its parent container.
android:layout_alignParentTop
android:layout_alignParentBottom
android:layout_alignParentLeft
android:layout_alignParentRight
android:layout_centerInParent
android:layout_centerVertical
android:layout_centerHorizontal
The Relative Layout
2. Referring to other widgets
The following properties managethe positioning of a widget respect to other
widgets:
android:layout_above=“@+id/wid1”
android:layout_below
android:layout_toLeftOf
android:layout_toRightOf
In this example widget “wid2” is map
relative to wid1 (knownas “@+id/wid1” )
wid2
wid1 wid2
only to
The Relative Layout
2. Referring to other widgets – cont.
android:layout_alignTop=“@+id/wid1” wid1
wid2
android:layout_alignBottom =“@+id/wid1”
android:layout_alignLeft=“@+id/wid1”
android:layout_alignRight=“@+id/wid1”
wid1
wid1
wid2
wid2
wid1
wid2
The Relative Layout
2. Referring to other widgets
When using relativepositioning you need to:
1. Use identifiers ( android:id attributes ) on all elements that you will be
referring to.
2. XML elements arenamed using the prefix:@+id/... For instancean
EditText box could be called: android:id="@+id/txtUserName"
3. You must refer l widgets that havebeen already defined.For instancea
new control to be positioned below the txtUserName EditText box could
refer to it using: android:layout_below="@+id/txtUserName"
The Relative Layout
2. Example
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/myRelativeLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ff000099" >
<TextView
android:id="@+id/lblUserName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:background="#ffff0066"
android:text="User Name"
android:textColor="#ff000000"
android:textStyle="bold" >
</TextView>
<EditText
android:id="@+id/txtUserName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/lblUserName"
android:padding="20dp" >
</EditText>
<Button
android:id="@+id/btnGo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="@+id/txtUserName"
android:layout_below="@+id/txtUserName"
android:text="Go"
android:textStyle="bold" >
</Button>
<Button
android:id="@+id/btnCancel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/txtUserName"
android:layout_toLeftOf="@+id/btnGo"
android:text="Cancel"
android:textStyle="bold" >
</Button>
</RelativeLayout>
The Table Layout
37
3. Table Layout
1. Android's TableLayout uses a grid to position your widgets.
2. Like in a matrix,cells in thegrid are identifiableby rows and columns.
3. Columns are flexible,they could shrink or stretch to accommodatetheir
contents.
4. The element TableRow is used to define a new row in which widgets can be
allocated.
5. The number of columns in a TableRowis determined by the total of side‐by‐
sidewidgets placed on the row.
Basic XML Layouts ‐ Containers
3. Table Layout – Setting Number of Columns
The number of columns in a row is determined by Android.
Example: If your TableLayouthavethree rows,one with two widgets, one with
three widgets, and one with four widgets, there will beatleastfour columns.
0 1
0 1 2
0 1 2 3
Basic XML Layouts ‐ Containers
3. Table Layout – Stretching a Column
• A singlewidget in a TableLayoutcan occupy more than one column.
• The android:layout_span property indicates thenumber of columns the
widget is allowed to expand.
<TableRow>
<TextView android:text="URL:" />
<EditText
android:id="@+id/entry"
android:layout_span="3" />
</TableRow>
Module IV
Sensors
Google Maps Android API V2
Tutorial – Hello GoogleMap
Based on: https://developers.google.com/maps/documentation/android/start
• We'll createa simpleActivity that shows a
simplemap.
• The map displays two markers:one
represents a location in Cleveland Ohio,and
the other is on San Jose Costa Rica.
• The markers areconnected by a straightline.
7
Tutorial – HelloGoogleMap
Based on: https://developers.google.com/maps/documentation/android/start
Part 1.
One Time Operation – Prepare your Eclipse Workspace
• Select File > Import > Android > Existing Android Code Into Workspace
and click Next.
• Select Browse..., enter <android-sdk-folder>/extras/google/google_play_services/
libproject/google-play-services_lib, and clickFinish.
Google Maps Android API V2
Tutorial – HelloGoogleMap
Based on: https://developers.google.com/maps/documentation/android/start
Part 1.
One Time Operation – Prepare your Eclipse Workspace
• After completing previous steps your
workspaceshould includea new project
called google-play-services_lib.
9
Google Maps Android API V2
Tutorial – HelloGoogleMap
Based on: https://developers.google.com/maps/documentation/android/start
Part 2. Creating the App
1. Create a newAndroid project, callit:HelloGoogleMap (minimum level API 11).
2. To establish a dependency between your Projectand Google Play Services,
do this (starting on the Eclipse’s toolbar):
Project > Properties> Android > Library> Add > google-play-services_lib
Google Maps Android API V2
Tutorial – HelloGoogleMap
Based on: https://developers.google.com/maps/documentation/android/start
Part 2. Creating the App
3. Check that anupdated Google_Play_Services lib isavailable onthe device (you will
need a ‘real’ workingdevice for testing, at this time the Emulator does not support
GMS mapping). Add the following statements to your onCreate(…) method
int result = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(
getApplicationContext());
if ( result != ConnectionResult.SUCCESS ) {
GooglePlayServicesUtil
.getErrorDialog(result, MainActivity.this, 1).show();
}
11
Google Maps Android API V2
Tutorial – HelloGoogleMap
Based on: https://developers.google.com/maps/documentation/android/start
Part 2. Creating the App
4. Update your layout res/layout/activity_main.xml. Replace its contents with:
<fragment
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
class="com.google.android.gms.maps.MapFragment" />
Google Maps Android API V2
Tutorial – HelloGoogleMap
Based on: https://developers.google.com/maps/documentation/android/start
Part 2. Creating the App
5. The @+id/map entry defined in the previous XML definition is
programmatically controlled through the GoogleMap map class level
variable.Add the following statementto your onCreate method.
map = ((MapFragment) getFragmentManager()
.findFragmentById(R.id.map))
.getMap();
6. Add the following lines into your AndroidManifest.xml (insertthem
before the first<Activity>tag)
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="Your-40-chars-API-KEY-goes-here" />
Google Maps Android API V2
Tutorial – HelloGoogleMap
Based on: https://developers.google.com/maps/documentation/android/start
Part 2. Creating the App
7. Modify the app’s AndroidManifest.xml filewith the following permissions and
features requests
<uses-feature
android:glEsVersion="0x00020000"
android:required="true" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="YOUR_PACKAGE_NAME.permission.MAPS_RECEIVE" />
<permission
android:name="YOUR_PACKAGE_NAME.permission.MAPS_RECEIVE"
android:protectionLevel="signature" />
Google Maps Android API V2
Tutorial – HelloGoogleMap
Based on:
https://developers.google.com/maps/documentation/android/start
Part 2. Creating the App
8. Testyour app. It shouldshowa mapof the
world centeredoncoordinates 00
,00
(Atlantic
Ocean, west of Africa)
9. Attribution Requirements.
“… you must include the Google PlayServices
attribution text as part of a "LegalNotices"
section inyour application.
Includinglegal notices as anindependent
menu item, or as part of an "About" menu
item, is recommended. The attribution text is
available bymaking a call to “
GooglePlayServicesUtil.getOpenSourceSoftwareLicenseInfo(context);
Google Maps Android API V2
Tutorial – HelloGoogleMap
Based on: https://developers.google.com/maps/documentation/android/start
Part 3. Improving the App – Adding a Marker
10. Modifyyour onCreate method. Adda callto the setUpMap method givenbelow
private void setUpMap () {
// test that we have a map already instantiated
if (map == null) {
map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
// Check if we were successful in obtaining the map.
if (map != null) {
// now it is now safe to manipulate the map.
map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
// disable indoor maps
map.setIndoorEnabled(false);
// this point represents location of Cleveland State University
LatLng CSU_OHIO = new LatLng(41.501936, -81.675278);
Marker csu_ohio_marker = map.addMarker(new MarkerOptions()
.position(CSU_OHIO)
.title("Cleveland State University")
.snippet("Cleveland, Ohio") );
map.moveCamera(CameraUpdateFactory.newLatLngZoom( CSU_OHIO, 15.0f ));
16
Google Maps Android API V2
Tutorial – HelloGoogleMap
Based on: https://developers.google.com/maps/documentation/android/start
Part 3. Improving the App – Adding a Marker
10. Continuation - setUpMap method:
// set up map UI settings:
UiSettings mapUI = map.getUiSettings();
// enable: pan, zoom, tilt, rotate
mapUI.setAllGesturesEnabled(true);
// enable compass
mapUI.setCompassEnabled(true);
// enable zoom controls
mapUI.setZoomControlsEnabled(true);
}
}
}// setUpMapIfNeeded
17
Google Maps Android API V2
Tutorial – HelloGoogleMap
Based on: https://developers.google.com/maps/documentation/android/start
Part 4. Improving the App – Adding PolyLines
11. Modifythe setUpMap method introduced inthe previous section. Replace the
statement map.movecamera... with the following next lines
// this marker represents Universidad de Costa Rica
LatLng SANJOSE1_CR = new LatLng(9.937931, -84.051936);
Marker san_jose1_marker = map.addMarker(new MarkerOptions()
.position(SANJOSE1_CR)
.title("Universidad de Costa Rica")
.snippet("San Jose, CR")
.icon(BitmapDescriptorFactory.defaultMarker(
BitmapDescriptorFactory.HUE_GREEN)) );
// drawing a straight line between the two points
Polyline line = map.addPolyline(new PolylineOptions()
.add( SANJOSE1_CR, CSU_OHIO )
.width(2)
.color(Color.BLUE));
// this point is halfway between Cleveland and San Jose
LatLng halfWay = new LatLng( (SANJOSE1_CR.latitude + CSU_OHIO.latitude)/2,
(SANJOSE1_CR.longitude + CSU_OHIO.longitude)/2 );
map.moveCamera( CameraUpdateFactory.newLatLngZoom( halfWay, 4.0f ) );
Tutorial –
HelloGoogleMap
Based on:
https://developers.google.com/maps/documentation/android/start
Part 4. Improving the App – Adding PolyLines
12. Test your application.
Module V
Bluetooth, NFC,
Networks, and
Wi-Fi
Creating a Bluetooth client socket
priva t e void connectT oSer verS ocket( Bl uet oothD evic e devi c e, UUID uuid) {
try{
BluetoothS ocket client S oc ke t
= device.crea teRf c om mS ocket T oSe r vi ceRe c or d(u ui d);
// Block until server connection accepte d.
clientSocket.connect();
// Start listening for messages.
listenF or M es s a ges ( c li e n t S oc ke t );
// Add a reference to the socket used to send messages.
transfe rS o ck et = clientSocket;
} catch (IOExcept i on e) {
Log.e(“BLU ETOO TH”, “Bluet oot h client I/O Except i on ”, e);
}
}
Sending and receiving strings using Bluetooth Sockets
priva t e void listenFor Me ssa ges( Bl u et ooth S ocke t socket ,
Strin gB u il d e r incoming) {
listening = true;
int buffer S i z e = 1024;
byte[] buffe r = new byte[bufferSize];
try {
InputStream instream = socket. ge t In pu t S tr ea m () ;
int bytesRead = -1;
while (listening) {
bytesRead = instr ea m . r e a d( bu f f e r) ;
if (bytesRead != -1) {
Strin g result = “”;
while ((bytesRea d == bufferSize) &&
(buffer[bufferSize-1] != 0)){
result = result + new String(buffer, 0, bytesRead - 1);
bytesRead = instr ea m . r e a d( bu f f e r) ;
}
result = result + new String(buffer, 0, bytesRead - 1);
incom i n g. a ppe n d( r es u lt );
}
socket.close();
}
} catch (IOExcept i on e) {
Log.e(TAG, “Message receive d failed.”, e);
}
finally {
}
}
Listening for NFC tags
<activity android:name= ”.B logVi ewer ”>
<intent-filter>
<action android:name= ”a ndroid. nfc.ac ti on. NDEF_DISCO VERED”/>
<category android:na me = ”an dr oi d.i nte nt. cat e gor y.DEFA U LT ”/ >
<data android:sch eme = ”htt p”
androi d: h os t = ”bl o g. ra di oa ct i ve ya k. c om ”/ >
</intent-filter>
</acti vi t y>
Extracting NFC tag payloads
Strin g action = getIntent().getAction();
if (NfcAdapter.ACTION_ NDEF_DISC OVERED.equals(acti on)) {
Parcelable[] messages =
intent.getP ar cel a ble Ar ra yE xtr a(Nf c A da pte r.E XT RA_ NDEF_ M ES SA GE S);
for (int i = 0; i < messages.le n gth ; i++) {
NdefMessage message = (NdefMessa ge) mes sa ges[ i];
NdefRecord[] records = message.ge tRe c or ds();
for (int j = 0; j < recor d s. l e n gt h ; j++) {
NdefRecord record = records[j];
// TODO Process the individual recor ds .
}
}
}
Module VI
I/O file
+ "n"
Android Files
Example 0: Reading a ResourceFile(see previous figure)
//reading an embedded RAW data file
public class File1Resources extends Activity {
TextView txtMsg;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
txtMsg = (TextView) findViewById(R.id.textView1);
try {
PlayWithRawFiles();
} catch (IOException e) {
txtMsg.setText( "Problems: " + e.getMessage() );
}
}// onCreate
7
Android Files
Example 1: Reading a ResourceFile(see previous figure)
public void PlayWithRawFiles() throws IOException {
String str="";
StringBuffer buf = new StringBuffer();
int fileResourceId = R.raw.my_text_file;
InputStream is = this.getResources().openRawResource(fileResourceId);
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
if (is!=null) {
while ((str = reader.readLine()) != null) {
buf.append(str );
}
}
is.close();
txtMsg.setText( buf.toString() );
}// PlayWithRawFiles
} // File1Resources 8
Android Files
Example 2: (Internal Storage ) Read/Write an Internal File.
In this example an application collects
data from the UI and saves itto a
persistentdata fileinto the (limited) internal
Android System spacearea.
Next time the application is executed the
Resource File will beread and its data shown
on the UI
9
Android Files
Example 2: (Internal Storage ) Read/Write an Internal File.
The internal resource file is private
and cannot be seen by other apps
residing in main memory.
Android Files
Example2: Grab data from screen, save to file, retrieve from file.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffdddddd"
android:padding="10dp"
android:orientation="vertical" >
<Button android:id="@+id/btnFinish"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:text=" Save File and Close " />
<EditText
android:id="@+id/txtMsg"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="10dp"
android:background="#ffffffff"
android:gravity="top"
android:hint="Enter some lines of data here..." />
</LinearLayout>
11
Android Files
Example 2: Grab data from screen, saveto file, retrieve from file 1/3.
public class File2WriteRead extends Activity {
private final static String FILE_NAME = "notes.txt";
private EditText txtMsg;
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
txtMsg = (EditText) findViewById(R.id.txtMsg);
// deleteFile(); //keep for debugging
Button btnFinish = (Button) findViewById(R.id.btnFinish);
btnFinish.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
finish();
}
});
}// onCreate
"/data/data/cis470 filewriteread/files/"
Android Files
Example 2: Grab data from screen, saveto file, retrieve from file 2/3.
public void onStart() {
super.onStart();
try {
InputStream inputStream = openFileInput(FILE_NAME);
if (inputStream != null) {
InputStreamReader inputStreamReader = new
InputStreamReader(inputStream);
BufferedReader reader = new BufferedReader(inputStreamReader);
String str = "READING FROM EXISTING DISKn";
StringBuffer stringBuffer = new StringBuffer();
while ((str = reader.readLine()) != null) {
stringBuffer.append(str + "n");
}
inputStream.close();
txtMsg.setText(stringBuffer.toString());
}
} catch (java.io.FileNotFoundException e) {
} catch (Throwable t) {
Toast.makeText(this, "Exception: " + t.toString(), 1).show();
}
}// onStart
13
Android Files
Example 2: Grab data from screen, saveto file, retrieve from file 3/3.
public void onPause() {
super.onPause();
try {
OutputStreamWriter out = new OutputStreamWriter(
openFileOutput(FILE_NAME, 0));
out.write(txtMsg.getText().toString());
out.close();
} catch (Throwable t) {
txtMsg.setText( t.getMessage() );
}
}// onPause
private void deleteFile() {
String path = /data/data/cis470.matos.filewriteread/files/ + FILE_NAME;
File f1 = new File(path);
Toast.makeText(getApplicationContext(), "Exists " + f1.exists() , 1).show();
boolean success = f1.delete();
if (!success){
Toast.makeText(getApplicationContext(), "Deletion failed.", 1).show();
}else{
Toast.makeText(getApplicationContext(), "OK. File deleted.", 1).show();
}
} 14
2
6
Module VII
Database
Example 1. Create a SQLite Database
package cis70.matos.sqldatabases;
public class SQLDemo1 extends Activity {
SQLiteDatabase db;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// this provides the 'real' path name to theexternal SD card
String SDcardPath = Environment.getExternalStorageDirectory().getPath();
// For internal memory: "data/data/cis470.matos.sqldatabases/myfriendsDB"
TextView txtMsg = (TextView)findViewById(R.id.txtMsg);
String myDbPath = SDcardPath + "/" + "myfriends";
txtMsg.setText("DB Path: " + myDbPath);
try {
db = SQLiteDatabase.openDatabase(myDbPath,
null,
SQLiteDatabase.CREATE_IF_NECESSARY);
// here you do something with your database ...
db.close();
txtMsg.append("nAll done!");
}
catch (SQLiteException e) {
txtMsg.append( e.getMessage() );
}
}//onCreate
}//class 7
SQL Databases
Example 1.
Create a SQLite Database
using Internal Memory
Android’s System Image:
/data/data/cis470.matos.sqldatabases/
myfriendsDB
8
SQL Databases
Example2
An alternative way of opening/creating a SQLITE database in your local
Android’s data space is given below
SQLiteDatabase db = this.openOrCreateDatabase(
"myfriendsDB",
MODE_PRIVATE,
null);
If this app is created in a namespace called “cis493.sql1”, the full nameof the
newly created databasefilewill be:
/data/data/cis493.sql1/databases/myfriendsDB
This filecould later beused by other activities in theapp or exported out of the
emulator (adb push…) and given to a tool such as SQLITE_ADMINISTRATOR (see
notes at the end).
SQL Databases
Example2
An alternative way of opening/creating a SQLITE database in your local
Android’s System Image is given below
SQLiteDatabase db = this.openOrCreateDatabase(
"myfriendsDB2",
MODE_PRIVATE,
null);
Where:
1. “myFriendsDB2” is the abbreviated filepath.The prefix is assigned by
Android as:/data/data/<app namespace>/databases/myFriendsDB2.
2. MODE could be: MODE_PRIVATE, MODE_WORLD_READABLE, and
MODE_WORLD_WRITEABLE. Meaningful for apps consisting of multiples
activities.
3. null refers to optional factory class parameter (skip for now)
Module VIII
Networking
Consuming Web Services
Example ‐ How .NET Web Services Are Called?
Our examplecode consists of two fragments which implement the server and
clientsideof the application.
Server Side:
• The document http://support.microsoft.com/kb/301273 describes howto
create a simpleWeb servicerunning on a Windows IIS‐Server.
Client Side:
• We use the KSOAP 2.0 platformto request a sequence of remote procedure
calls to the IIS server hosting our servicecode.
• The methods includefunctions taking zero,or more arguments.
• Arguments send/received can be simpledata types or complex objects.
http://code.google.com/p/ksoap2‐android/
http://www.java2s.com/Code/Jar/k/Downloadksoap2base254jar.htm
Consuming Web Services
Example ‐ How .NET Web Services Are Called?
KSOAP2 Documentation & Download
http://code.google.com/p/ksoap2‐android/
http://code.google.com/p/ksoap2‐android/source/browse/m2‐
repo/com/google/code/ksoap2‐android/ksoap2‐android‐assembly/2.5.5/
http://www.java2s.com/Code/Jar/k/Downloadksoap2base254jar.htm
Hosting Solution
There are several options for externally hosting your .NET solution,registration
strategy varies.Some Providers are:
1. http://www.asp.net/hosting
2. www.somee.com
Consuming Web Services
Example – TUTORIAL – IIS Server Side Code
Services Available at the IIS Server
Consuming Web Services
Example – TUTORIAL – IIS Server Side Code
Android App accessing
all services available
at the IIS server
Consuming Web Services
Example – TUTORIAL – Android Application
Our Android app uses KSOAP 2 API. KSOAP is a webservice client library for
constrained Java environments. SOAP protocol is widely used for machine‐
to‐machine interaction, it is strong‐typed and supports synchronous,
asynchronous, and complex‐routing communication schemes.
Our implementation includes three classes
1. Main webcalls areassembled
2. EnglishDistance (Serialized Class)
3. WebServiceCall deals with HTTP
transporting of the
request/response
and envelope objects
Consuming Web Services
Example – TUTORIAL – Android Application
A fragmentof the Android Mainclassfollows
public class Main extends Activity {
public TextView txtMsg;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
txtMsg = (TextView)findViewById(R.id.txtMsg);
WebServiceCall webServiceCall = new WebServiceCall();
// add two numbers - get int result
int intResult = webServiceCall.AddService(11, 22);
txtMsg.append( "nAdd RESULT= " + intResult );
}
All the intelligentworkisdone bythe WebServiceCall class.
Consuming Web Services
Example – TUTORIAL – Android Application
The WebServiceCall classnegotiates the transporting ofrequest/responseobjects as well
as preparation of serialization of complex data elements ( 1/4 )
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import android.util.Log;
public class WebServiceCall
{
private static final String SOAP_ACTION = "http://tempuri1.org/";
private static final String NAMESPACE = "http://tempuri1.org/";
private static final String URL =
"http://iamok.somee.com/MathService.asmx";
protected Object call( String soapAction,
SoapSerializationEnvelope envelope)
{
Consuming Web Services
Example – TUTORIAL – Android Application
WebServiceCall class (continuation 2/4)
Object result = null;
final HttpTransportSE transportSE = new HttpTransportSE(URL);
transportSE.debug = false;
// call and Parse Result.
try
{
transportSE.call(soapAction, envelope);
result = envelope.getResponse();
} catch (final Exception e)
{
Log.e("<<Exception>>",e.getMessage());
}
return result;
}
Consuming Web Services
Example 1 – TUTORIAL – Android Application
Fragmentof the WebServiceCall class called to add twonumbers. Here input parameters
and output valuesresultingfromthe webservice are sent andreceived. (cont. 3/4)
public int AddService(int v1, int v2){
int intResult = 0;
// indicate webservice (endpoint) to be called
final String webMethod = "Add";
// Create the outgoing request message
final SoapObject requestObject = new SoapObject(NAMESPACE,
webMethod);
// add outgoing parameters (name-type must agree with endpoint)
requestObject.addProperty("v1", v1);
requestObject.addProperty("v2", v2);
// Create soap envelope for .NET server
final SoapSerializationEnvelope envelope =
new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
// place in envelope the outgoing request object
envelope.setOutputSoapObject(requestObject);
Consuming Web Services
Example 1 – TUTORIAL – Android Application
The WebServiceCall class (continuation 4/4)
try
{
Web
service is
called here
// call webmethod and parse returning response object
final Object response = (Object) this.call(
SOAP_ACTION + webMethod,
envelope);
if (response != null)
intResult = Integer.parseInt(response.toString());
} catch (Exception e)
{
Log.e("<<Exception-Add>>",e.getMessage());
}
return intResult;
}
}
Module IX
Developing Android
Services
1. Using Eclipse, create a new Android project and name it Services
2. Add a new Java Class file to the project and name it MyService. Populate the MyService.java file
with the following code:
package net.le a r n 2 de ve l o p.S e r vi c e s;
import android.a pp.Se rv ice;
import android.conte nt.I nte nt;
import android.os.I Binder;
import android.widget.Toas t;
public class MyService extends Service {
@Override
public IBinder onBind(Intent arg0) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startI d) {
// We want this service to continue running until it is explicitly
// stopped, so return sticky.
Toast.makeText(th is , “Service Started”, Toast.LENGTH_LONG).s how ();
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDes troy();
Toast.makeText(th is , “Service Destroyed”, Toast.LENGTH_LONG).s ho w();
}
}
3. In the An droidMan ifest.xml file, add the following statement in bold:
<?xml version= ”1.0” encodin g=”utf-8”?>
<manifest xmlns:androi d=”h tt p://s c he m as. an dr oi d. c om/a pk/r es/ an dr oi d”
package=” n et . le a r n 2 de ve l op. Se r vi c e s ”
android:versi onC ode = ”1 ”
android:version Name= ”1.0” >
<uses-sdk android:minSdkV ersi on = ”1 4 ” />
<appli ca ti o n
android:i c on =”@ drawa ble/i c_ lau n c her ”
androi d: la be l = ”@ string/app_name” >
<activity
androi d: la be l = ”@ string/app_name”
android:name=”.ServicesActivity” >
<intent-filter >
<action android:name= ”a n dr oi d. i nt e n t.a c ti o n. M AIN ” />
<category android:name=”an dr oi d. in te nt. cat e gor y. L A UN CHER ” />
</intent-filter>
</acti vi t y>
<service android:name=”.MyService” />
</applica ti on >
</manifest>
4. In the main .xml file, add the following statements in bold, replacing TextView :
<?xml version= ”1.0” encodin g=”utf-8”?>
<LinearLayout xmlns:androi d= ”ht t p:// s ch e ma s.a n dr oi d.c o m/a pk/ re s/a n dr oi d”
android: la yout _wi dt h =”fill_parent”
androi d:l a yout _h ei gh t = ”fill_parent”
androi d: or ie n ta ti on = ”vertical” >
<Button android:id= ”@+id/btnStartService”
android:layout_w idth= ”fill_ pa re nt”
android:layout_ height= ”w rap_content”
android:text= ”Sta rt Service”
android:onClick=”sta rtS e rv ice ”/>
<Button android:id= ”@+id/btnStopService”
android:layout_w idth= ”fill_ pa re nt”
android:layout_ height= ”w rap_content”
android:text= ”Stop Service”
android:onClick=”stopSe rv ice ” />
</LinearLayout >
5. Add the following statements in bold to the ServicesActivity.java file:
package net.le a r n 2 de ve l o p.S e r vi c e s;
import android.app.Activity;
import android.conte nt.I nte nt;
import androi d. os. B u n dl e;
import android.view .Vie w;
public class ServicesActivity extends Activity {
/** Called when the activity is first create d. */
@Override
public void onCreate(Bundle savedIn st a n ce St at e) {
super. on C r ea te (s a ve dIn st a n c eS t at e) ;
setConte n tV ie w( R.l a you t. main);
}
public void startService(V ie w view) {
startSe rv ice ( new Intent(getBase Conte xt(), MyService.clas s ));
}
public void stopService(View view) {
stopService( new Intent(getBase Conte xt(),
MyService.clas s ));
}
}
6. Press F11 to debug the application on the Android
emulator.
7. Clicking the Start Service button will start the service. To
stop the service, click the Stop Service button.
Module X
Audio and Video
MediaPlayer – Playing Audio from a Raw Resource
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/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="Humble Media Player"
android:textStyle="bold"/>
<Button android:id="@+id/playsong"
android:layout_width="80px"
android:layout_height="wrap_content"
android:text="PLAY Music"/>
<Button android:id="@+id/stopsong"
android:layout_width="80px"
android:layout_height="wrap_content"
android:text="STOPMusic"/>
</LinearLayout>
//MyMediaPlayer Demo1: plays a song saved as a RAW resource
//------------------------------------------------------------------------
package cis493.multimedia;
import android.app.Activity;
import android.os.Bundle;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MyMediaPlayer extends Activity {
MediaPlayer mp;
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
Button myPlayButton = (Button) findViewById(R.id.playsong);
Button myPlayButton = (Button)
findViewById(R.id.playsong);
myPlayButton.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
try {
mp = MediaPlayer.create(MyMediaPlayer.this,
R.raw.beethoven_symphony_9);
mp.start();
mp.setOnCompletionListener(new
OnCompletionListener() {
public void onCompletion(MediaPlayer arg0) {
Toast.makeText(getApplicationContext(),"Br
avo! Bravo!", 1).show();
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
});// myPlayButton
Button myStopButton = (Button) findViewById(R.id.stopsong);
myStopButton.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
if (mp.isPlaying()) {
mp.stop();
}
}// onClick
}); // myStopButton
}// onCreate
}

Weitere ähnliche Inhalte

Was ist angesagt?

Dell Vostro 3568 Laptops Trần Phát
Dell Vostro 3568 Laptops Trần PhátDell Vostro 3568 Laptops Trần Phát
Dell Vostro 3568 Laptops Trần PhátLAPTOP TRẦN PHÁT
 
In designcs5 scripting tutorial
In designcs5 scripting tutorialIn designcs5 scripting tutorial
In designcs5 scripting tutorialMustfeez Rasul
 
Dell chassis-management-controller-v610-poweredge-m1000e users-guide-en-us
Dell chassis-management-controller-v610-poweredge-m1000e users-guide-en-usDell chassis-management-controller-v610-poweredge-m1000e users-guide-en-us
Dell chassis-management-controller-v610-poweredge-m1000e users-guide-en-ushuyvuquang7
 
ZebraNet Bridge Enterprise - Manual do Software
ZebraNet Bridge Enterprise - Manual do SoftwareZebraNet Bridge Enterprise - Manual do Software
ZebraNet Bridge Enterprise - Manual do SoftwareUseZ
 
Selenium documentation,
Selenium documentation,Selenium documentation,
Selenium documentation,t7t7uyt
 
Oracle® Fusion Middleware
Oracle® Fusion MiddlewareOracle® Fusion Middleware
Oracle® Fusion MiddlewareNgo Hung Long
 
AI Dominoes Project
AI Dominoes ProjectAI Dominoes Project
AI Dominoes ProjectAdil Gasimov
 
Dcp 2000 field-instmanual_000344_v1_5
Dcp 2000 field-instmanual_000344_v1_5Dcp 2000 field-instmanual_000344_v1_5
Dcp 2000 field-instmanual_000344_v1_5xacho1
 
Zend framework 1.10.x English
Zend framework 1.10.x EnglishZend framework 1.10.x English
Zend framework 1.10.x EnglishMostafa Mahmoud
 
Enabling mobile apps with ibm worklight application center red
Enabling mobile apps with ibm worklight application center redEnabling mobile apps with ibm worklight application center red
Enabling mobile apps with ibm worklight application center redbupbechanhgmail
 
Man 00851 rev 001 understanding image checker 9.0
Man 00851 rev 001 understanding image checker 9.0Man 00851 rev 001 understanding image checker 9.0
Man 00851 rev 001 understanding image checker 9.0alex123123123
 

Was ist angesagt? (20)

Accelerometer
Accelerometer Accelerometer
Accelerometer
 
Dell Vostro 3568 Laptops Trần Phát
Dell Vostro 3568 Laptops Trần PhátDell Vostro 3568 Laptops Trần Phát
Dell Vostro 3568 Laptops Trần Phát
 
Report-V1.5_with_comments
Report-V1.5_with_commentsReport-V1.5_with_comments
Report-V1.5_with_comments
 
In designcs5 scripting tutorial
In designcs5 scripting tutorialIn designcs5 scripting tutorial
In designcs5 scripting tutorial
 
ISVForce Guide NEW
ISVForce Guide NEWISVForce Guide NEW
ISVForce Guide NEW
 
MySQL Query Browser
MySQL Query BrowserMySQL Query Browser
MySQL Query Browser
 
Dell chassis-management-controller-v610-poweredge-m1000e users-guide-en-us
Dell chassis-management-controller-v610-poweredge-m1000e users-guide-en-usDell chassis-management-controller-v610-poweredge-m1000e users-guide-en-us
Dell chassis-management-controller-v610-poweredge-m1000e users-guide-en-us
 
Windowstweaksguide updated
Windowstweaksguide updatedWindowstweaksguide updated
Windowstweaksguide updated
 
Qtp user-guide
Qtp user-guideQtp user-guide
Qtp user-guide
 
Win8 accessibility tutorials
Win8 accessibility tutorialsWin8 accessibility tutorials
Win8 accessibility tutorials
 
ZebraNet Bridge Enterprise - Manual do Software
ZebraNet Bridge Enterprise - Manual do SoftwareZebraNet Bridge Enterprise - Manual do Software
ZebraNet Bridge Enterprise - Manual do Software
 
Selenium documentation,
Selenium documentation,Selenium documentation,
Selenium documentation,
 
Oracle® Fusion Middleware
Oracle® Fusion MiddlewareOracle® Fusion Middleware
Oracle® Fusion Middleware
 
AI Dominoes Project
AI Dominoes ProjectAI Dominoes Project
AI Dominoes Project
 
Dcp 2000 field-instmanual_000344_v1_5
Dcp 2000 field-instmanual_000344_v1_5Dcp 2000 field-instmanual_000344_v1_5
Dcp 2000 field-instmanual_000344_v1_5
 
Acro js guide
Acro js guideAcro js guide
Acro js guide
 
Zend framework 1.10.x English
Zend framework 1.10.x EnglishZend framework 1.10.x English
Zend framework 1.10.x English
 
Enabling mobile apps with ibm worklight application center red
Enabling mobile apps with ibm worklight application center redEnabling mobile apps with ibm worklight application center red
Enabling mobile apps with ibm worklight application center red
 
Man 00851 rev 001 understanding image checker 9.0
Man 00851 rev 001 understanding image checker 9.0Man 00851 rev 001 understanding image checker 9.0
Man 00851 rev 001 understanding image checker 9.0
 
Autocad 2000 manual
Autocad 2000 manualAutocad 2000 manual
Autocad 2000 manual
 

Andere mochten auch

Bluetooth Smart (Low Energy) for Android
Bluetooth Smart (Low Energy) for AndroidBluetooth Smart (Low Energy) for Android
Bluetooth Smart (Low Energy) for AndroidLocalz
 
Parque Nacional De Los Montes Virunga
Parque Nacional De Los Montes VirungaParque Nacional De Los Montes Virunga
Parque Nacional De Los Montes Virungaangrba
 
Mundo clásico en el vino de Rioja.
Mundo clásico en el vino de Rioja.Mundo clásico en el vino de Rioja.
Mundo clásico en el vino de Rioja.Clara Álvarez
 
Personalidades
PersonalidadesPersonalidades
PersonalidadesElo Isa
 
Technologie IMRS, SwissBionic
Technologie IMRS, SwissBionicTechnologie IMRS, SwissBionic
Technologie IMRS, SwissBionicEric Comandé
 
New Orleans Zephyrs Media kit
New Orleans Zephyrs Media kitNew Orleans Zephyrs Media kit
New Orleans Zephyrs Media kitsarahfwasser
 
Fuentes secundarias para el historiador. Una reflexión a partir de lo digital...
Fuentes secundarias para el historiador. Una reflexión a partir de lo digital...Fuentes secundarias para el historiador. Una reflexión a partir de lo digital...
Fuentes secundarias para el historiador. Una reflexión a partir de lo digital...Pablo Folgueira Lombardero
 
Tips to better skin without spending any money
Tips to better skin without spending any moneyTips to better skin without spending any money
Tips to better skin without spending any moneySheena Agarwal
 
Presentacion comercial TRISON 2014
Presentacion comercial TRISON 2014Presentacion comercial TRISON 2014
Presentacion comercial TRISON 2014Trison_Acustica
 
Decoria catalog
Decoria catalogDecoria catalog
Decoria catalogKavaler
 
Libro Mejora tu Salud de Alvaro Iglesias - El PH en el Organismo
Libro Mejora tu Salud  de  Alvaro Iglesias  -  El PH en el OrganismoLibro Mejora tu Salud  de  Alvaro Iglesias  -  El PH en el Organismo
Libro Mejora tu Salud de Alvaro Iglesias - El PH en el OrganismoNicolás Alzaga Ruiz
 
Manual para evaluar_planteles_por_ingreso_al_snb
Manual para evaluar_planteles_por_ingreso_al_snbManual para evaluar_planteles_por_ingreso_al_snb
Manual para evaluar_planteles_por_ingreso_al_snbmiguelafi
 

Andere mochten auch (20)

Bluetooth Smart (Low Energy) for Android
Bluetooth Smart (Low Energy) for AndroidBluetooth Smart (Low Energy) for Android
Bluetooth Smart (Low Energy) for Android
 
Besos Famosos
Besos  FamososBesos  Famosos
Besos Famosos
 
Parque Nacional De Los Montes Virunga
Parque Nacional De Los Montes VirungaParque Nacional De Los Montes Virunga
Parque Nacional De Los Montes Virunga
 
Mundo clásico en el vino de Rioja.
Mundo clásico en el vino de Rioja.Mundo clásico en el vino de Rioja.
Mundo clásico en el vino de Rioja.
 
Personalidades
PersonalidadesPersonalidades
Personalidades
 
Revista Rusa Russian Inn marzo abril 2014
Revista Rusa Russian Inn marzo abril 2014Revista Rusa Russian Inn marzo abril 2014
Revista Rusa Russian Inn marzo abril 2014
 
Technologie IMRS, SwissBionic
Technologie IMRS, SwissBionicTechnologie IMRS, SwissBionic
Technologie IMRS, SwissBionic
 
New Orleans Zephyrs Media kit
New Orleans Zephyrs Media kitNew Orleans Zephyrs Media kit
New Orleans Zephyrs Media kit
 
Fuentes secundarias para el historiador. Una reflexión a partir de lo digital...
Fuentes secundarias para el historiador. Una reflexión a partir de lo digital...Fuentes secundarias para el historiador. Una reflexión a partir de lo digital...
Fuentes secundarias para el historiador. Una reflexión a partir de lo digital...
 
Revista final festa vallmoll
Revista final festa vallmollRevista final festa vallmoll
Revista final festa vallmoll
 
Tips to better skin without spending any money
Tips to better skin without spending any moneyTips to better skin without spending any money
Tips to better skin without spending any money
 
Refranero Popular
Refranero PopularRefranero Popular
Refranero Popular
 
C.25-10 CS Recommends Amendments to Cheese Regulation
C.25-10 CS Recommends Amendments to Cheese RegulationC.25-10 CS Recommends Amendments to Cheese Regulation
C.25-10 CS Recommends Amendments to Cheese Regulation
 
Riesgos sísmicos
Riesgos sísmicosRiesgos sísmicos
Riesgos sísmicos
 
Presentacion comercial TRISON 2014
Presentacion comercial TRISON 2014Presentacion comercial TRISON 2014
Presentacion comercial TRISON 2014
 
Decoria catalog
Decoria catalogDecoria catalog
Decoria catalog
 
Libro Mejora tu Salud de Alvaro Iglesias - El PH en el Organismo
Libro Mejora tu Salud  de  Alvaro Iglesias  -  El PH en el OrganismoLibro Mejora tu Salud  de  Alvaro Iglesias  -  El PH en el Organismo
Libro Mejora tu Salud de Alvaro Iglesias - El PH en el Organismo
 
Ar condicionado apresentacao michelena climatizacao - Outrubro 2013
Ar condicionado   apresentacao michelena climatizacao - Outrubro 2013Ar condicionado   apresentacao michelena climatizacao - Outrubro 2013
Ar condicionado apresentacao michelena climatizacao - Outrubro 2013
 
Manual para evaluar_planteles_por_ingreso_al_snb
Manual para evaluar_planteles_por_ingreso_al_snbManual para evaluar_planteles_por_ingreso_al_snb
Manual para evaluar_planteles_por_ingreso_al_snb
 
ISO 14064
ISO 14064ISO 14064
ISO 14064
 

Ähnlich wie Android Programing Course Material Labs

Android chapter02-setup1-sdk
Android chapter02-setup1-sdkAndroid chapter02-setup1-sdk
Android chapter02-setup1-sdkTran Le Hoan
 
How to create android applications
How to create android applicationsHow to create android applications
How to create android applicationsTOPS Technologies
 
Final NEWS.pdf
Final NEWS.pdfFinal NEWS.pdf
Final NEWS.pdfRebaMaheen
 
Final NewsApp.pdf
Final NewsApp.pdfFinal NewsApp.pdf
Final NewsApp.pdfRebaMaheen
 
Android the first app - hello world - copy
Android   the first app - hello world - copyAndroid   the first app - hello world - copy
Android the first app - hello world - copyDeepa Rani
 
Interfacing android with embedded systems
Interfacing android with embedded systemsInterfacing android with embedded systems
Interfacing android with embedded systemsRaghav Shetty
 
Android tutorial
Android tutorialAndroid tutorial
Android tutorialDanish_k
 
Android tutorial
Android tutorialAndroid tutorial
Android tutorialmaster760
 
Android styles and themes
Android   styles and themesAndroid   styles and themes
Android styles and themesDeepa Rani
 
Android software development – the first few hours
Android software development – the first few hoursAndroid software development – the first few hours
Android software development – the first few hourssjmarsh
 
Bai thuc hanh lap trinh Android so 1
Bai thuc hanh lap trinh Android so 1Bai thuc hanh lap trinh Android so 1
Bai thuc hanh lap trinh Android so 1Frank Pham
 
Creating the first app with android studio
Creating the first app with android studioCreating the first app with android studio
Creating the first app with android studioParinita03
 

Ähnlich wie Android Programing Course Material Labs (20)

Android development module
Android development moduleAndroid development module
Android development module
 
Android course (lecture2)
Android course (lecture2)Android course (lecture2)
Android course (lecture2)
 
Android chapter02-setup1-sdk
Android chapter02-setup1-sdkAndroid chapter02-setup1-sdk
Android chapter02-setup1-sdk
 
Android wear notes
Android wear notesAndroid wear notes
Android wear notes
 
Android wear notes
Android wear notesAndroid wear notes
Android wear notes
 
How to create android applications
How to create android applicationsHow to create android applications
How to create android applications
 
Final NEWS.pdf
Final NEWS.pdfFinal NEWS.pdf
Final NEWS.pdf
 
Final NewsApp.pdf
Final NewsApp.pdfFinal NewsApp.pdf
Final NewsApp.pdf
 
Android the first app - hello world - copy
Android   the first app - hello world - copyAndroid   the first app - hello world - copy
Android the first app - hello world - copy
 
Bird.pdf
 Bird.pdf Bird.pdf
Bird.pdf
 
Interfacing android with embedded systems
Interfacing android with embedded systemsInterfacing android with embedded systems
Interfacing android with embedded systems
 
Build Your First Android App
Build Your First Android AppBuild Your First Android App
Build Your First Android App
 
Android tutorial
Android tutorialAndroid tutorial
Android tutorial
 
Android tutorial
Android tutorialAndroid tutorial
Android tutorial
 
Android tutorial
Android tutorialAndroid tutorial
Android tutorial
 
Android styles and themes
Android   styles and themesAndroid   styles and themes
Android styles and themes
 
Android software development – the first few hours
Android software development – the first few hoursAndroid software development – the first few hours
Android software development – the first few hours
 
Bai thuc hanh lap trinh Android so 1
Bai thuc hanh lap trinh Android so 1Bai thuc hanh lap trinh Android so 1
Bai thuc hanh lap trinh Android so 1
 
Creating the first app with android studio
Creating the first app with android studioCreating the first app with android studio
Creating the first app with android studio
 
Android tutorial
Android tutorialAndroid tutorial
Android tutorial
 

Mehr von Shady Selim

What is Kotlin Multiplaform? Why & How?
What is Kotlin Multiplaform? Why & How? What is Kotlin Multiplaform? Why & How?
What is Kotlin Multiplaform? Why & How? Shady Selim
 
Kotlin native for iOS and Android
Kotlin native for iOS and AndroidKotlin native for iOS and Android
Kotlin native for iOS and AndroidShady Selim
 
Introduction on Mobile development
Introduction on Mobile developmentIntroduction on Mobile development
Introduction on Mobile developmentShady Selim
 
Game development using Flutter
Game development using FlutterGame development using Flutter
Game development using FlutterShady Selim
 
I/O 2019 android updates
I/O 2019 android updatesI/O 2019 android updates
I/O 2019 android updatesShady Selim
 
Kotlin for android 2019
Kotlin for android 2019Kotlin for android 2019
Kotlin for android 2019Shady Selim
 
What's new in android 2018 (dev fest)
What's new in android 2018 (dev fest)What's new in android 2018 (dev fest)
What's new in android 2018 (dev fest)Shady Selim
 
Intro to Flutter
Intro to FlutterIntro to Flutter
Intro to FlutterShady Selim
 
Intro to kotlin 2018
Intro to kotlin 2018Intro to kotlin 2018
Intro to kotlin 2018Shady Selim
 
The magic of flutter
The magic of flutterThe magic of flutter
The magic of flutterShady Selim
 
Intro to Kotlin Minia GDG DevFest 2017
Intro to Kotlin Minia GDG DevFest 2017Intro to Kotlin Minia GDG DevFest 2017
Intro to Kotlin Minia GDG DevFest 2017Shady Selim
 
Kotlin for Frontend & Backend Web development
Kotlin for Frontend & Backend Web developmentKotlin for Frontend & Backend Web development
Kotlin for Frontend & Backend Web developmentShady Selim
 
Kotlin for android
Kotlin for androidKotlin for android
Kotlin for androidShady Selim
 
Android content provider explained
Android content provider explainedAndroid content provider explained
Android content provider explainedShady Selim
 
Design for Web and Mobile
Design for Web and MobileDesign for Web and Mobile
Design for Web and MobileShady Selim
 
Towards a better higher education system by Shady Selim
Towards a better higher education system by Shady SelimTowards a better higher education system by Shady Selim
Towards a better higher education system by Shady SelimShady Selim
 

Mehr von Shady Selim (20)

What is Kotlin Multiplaform? Why & How?
What is Kotlin Multiplaform? Why & How? What is Kotlin Multiplaform? Why & How?
What is Kotlin Multiplaform? Why & How?
 
Kotlin native for iOS and Android
Kotlin native for iOS and AndroidKotlin native for iOS and Android
Kotlin native for iOS and Android
 
Introduction on Mobile development
Introduction on Mobile developmentIntroduction on Mobile development
Introduction on Mobile development
 
Game development using Flutter
Game development using FlutterGame development using Flutter
Game development using Flutter
 
I/O 2019 android updates
I/O 2019 android updatesI/O 2019 android updates
I/O 2019 android updates
 
Kotlin for android 2019
Kotlin for android 2019Kotlin for android 2019
Kotlin for android 2019
 
What's new in android 2018 (dev fest)
What's new in android 2018 (dev fest)What's new in android 2018 (dev fest)
What's new in android 2018 (dev fest)
 
Intro to Flutter
Intro to FlutterIntro to Flutter
Intro to Flutter
 
Intro to kotlin 2018
Intro to kotlin 2018Intro to kotlin 2018
Intro to kotlin 2018
 
The magic of flutter
The magic of flutterThe magic of flutter
The magic of flutter
 
Intro to Kotlin
Intro to KotlinIntro to Kotlin
Intro to Kotlin
 
Intro to Kotlin Minia GDG DevFest 2017
Intro to Kotlin Minia GDG DevFest 2017Intro to Kotlin Minia GDG DevFest 2017
Intro to Kotlin Minia GDG DevFest 2017
 
Kotlin for Frontend & Backend Web development
Kotlin for Frontend & Backend Web developmentKotlin for Frontend & Backend Web development
Kotlin for Frontend & Backend Web development
 
Kotlin for android
Kotlin for androidKotlin for android
Kotlin for android
 
Intro to Kotlin
Intro to KotlinIntro to Kotlin
Intro to Kotlin
 
Firebase
FirebaseFirebase
Firebase
 
Android content provider explained
Android content provider explainedAndroid content provider explained
Android content provider explained
 
Design for Web and Mobile
Design for Web and MobileDesign for Web and Mobile
Design for Web and Mobile
 
Towards a better higher education system by Shady Selim
Towards a better higher education system by Shady SelimTowards a better higher education system by Shady Selim
Towards a better higher education system by Shady Selim
 
Cross mobility
Cross mobilityCross mobility
Cross mobility
 

Kürzlich hochgeladen

Call US Pooja 9892124323 ✓Call Girls In Mira Road ( Mumbai ) secure service,
Call US Pooja 9892124323 ✓Call Girls In Mira Road ( Mumbai ) secure service,Call US Pooja 9892124323 ✓Call Girls In Mira Road ( Mumbai ) secure service,
Call US Pooja 9892124323 ✓Call Girls In Mira Road ( Mumbai ) secure service,Pooja Nehwal
 
CALL ON ➥8923113531 🔝Call Girls Saharaganj Lucknow best sexual service
CALL ON ➥8923113531 🔝Call Girls Saharaganj Lucknow best sexual serviceCALL ON ➥8923113531 🔝Call Girls Saharaganj Lucknow best sexual service
CALL ON ➥8923113531 🔝Call Girls Saharaganj Lucknow best sexual serviceanilsa9823
 
BDSM⚡Call Girls in Sector 71 Noida Escorts >༒8448380779 Escort Service
BDSM⚡Call Girls in Sector 71 Noida Escorts >༒8448380779 Escort ServiceBDSM⚡Call Girls in Sector 71 Noida Escorts >༒8448380779 Escort Service
BDSM⚡Call Girls in Sector 71 Noida Escorts >༒8448380779 Escort ServiceDelhi Call girls
 
FULL ENJOY - 9999218229 Call Girls in {Mahipalpur}| Delhi NCR
FULL ENJOY - 9999218229 Call Girls in {Mahipalpur}| Delhi NCRFULL ENJOY - 9999218229 Call Girls in {Mahipalpur}| Delhi NCR
FULL ENJOY - 9999218229 Call Girls in {Mahipalpur}| Delhi NCRnishacall1
 
9892124323 | Book Call Girls in Juhu and escort services 24x7
9892124323 | Book Call Girls in Juhu and escort services 24x79892124323 | Book Call Girls in Juhu and escort services 24x7
9892124323 | Book Call Girls in Juhu and escort services 24x7Pooja Nehwal
 
CALL ON ➥8923113531 🔝Call Girls Gomti Nagar Lucknow best Night Fun service
CALL ON ➥8923113531 🔝Call Girls Gomti Nagar Lucknow best Night Fun serviceCALL ON ➥8923113531 🔝Call Girls Gomti Nagar Lucknow best Night Fun service
CALL ON ➥8923113531 🔝Call Girls Gomti Nagar Lucknow best Night Fun serviceanilsa9823
 
Powerful Love Spells in Arkansas, AR (310) 882-6330 Bring Back Lost Lover
Powerful Love Spells in Arkansas, AR (310) 882-6330 Bring Back Lost LoverPowerful Love Spells in Arkansas, AR (310) 882-6330 Bring Back Lost Lover
Powerful Love Spells in Arkansas, AR (310) 882-6330 Bring Back Lost LoverPsychicRuben LoveSpells
 

Kürzlich hochgeladen (7)

Call US Pooja 9892124323 ✓Call Girls In Mira Road ( Mumbai ) secure service,
Call US Pooja 9892124323 ✓Call Girls In Mira Road ( Mumbai ) secure service,Call US Pooja 9892124323 ✓Call Girls In Mira Road ( Mumbai ) secure service,
Call US Pooja 9892124323 ✓Call Girls In Mira Road ( Mumbai ) secure service,
 
CALL ON ➥8923113531 🔝Call Girls Saharaganj Lucknow best sexual service
CALL ON ➥8923113531 🔝Call Girls Saharaganj Lucknow best sexual serviceCALL ON ➥8923113531 🔝Call Girls Saharaganj Lucknow best sexual service
CALL ON ➥8923113531 🔝Call Girls Saharaganj Lucknow best sexual service
 
BDSM⚡Call Girls in Sector 71 Noida Escorts >༒8448380779 Escort Service
BDSM⚡Call Girls in Sector 71 Noida Escorts >༒8448380779 Escort ServiceBDSM⚡Call Girls in Sector 71 Noida Escorts >༒8448380779 Escort Service
BDSM⚡Call Girls in Sector 71 Noida Escorts >༒8448380779 Escort Service
 
FULL ENJOY - 9999218229 Call Girls in {Mahipalpur}| Delhi NCR
FULL ENJOY - 9999218229 Call Girls in {Mahipalpur}| Delhi NCRFULL ENJOY - 9999218229 Call Girls in {Mahipalpur}| Delhi NCR
FULL ENJOY - 9999218229 Call Girls in {Mahipalpur}| Delhi NCR
 
9892124323 | Book Call Girls in Juhu and escort services 24x7
9892124323 | Book Call Girls in Juhu and escort services 24x79892124323 | Book Call Girls in Juhu and escort services 24x7
9892124323 | Book Call Girls in Juhu and escort services 24x7
 
CALL ON ➥8923113531 🔝Call Girls Gomti Nagar Lucknow best Night Fun service
CALL ON ➥8923113531 🔝Call Girls Gomti Nagar Lucknow best Night Fun serviceCALL ON ➥8923113531 🔝Call Girls Gomti Nagar Lucknow best Night Fun service
CALL ON ➥8923113531 🔝Call Girls Gomti Nagar Lucknow best Night Fun service
 
Powerful Love Spells in Arkansas, AR (310) 882-6330 Bring Back Lost Lover
Powerful Love Spells in Arkansas, AR (310) 882-6330 Bring Back Lost LoverPowerful Love Spells in Arkansas, AR (310) 882-6330 Bring Back Lost Lover
Powerful Love Spells in Arkansas, AR (310) 882-6330 Bring Back Lost Lover
 

Android Programing Course Material Labs

  • 2. Table of Contents Module I.............................................................................................................................. 2 Getting Started.................................................................................................................. 2 Module II............................................................................................................................. 2 Activities, Fragments,....................................................................................................... 2 and Intents......................................................................................................................... 2 Module III............................................................................................................................ 2 Android User Interface..................................................................................................... 2 Module IV........................................................................................................................... 2 Sensors.............................................................................................................................. 2 Module V............................................................................................................................ 2 Bluetooth, NFC, Networks, and...................................................................................... 2 Wi-Fi.................................................................................................................................... 2 Module VI ........................................................................................................................... 2 I/O file ................................................................................................................................. 2 Module VII .......................................................................................................................... 2 Database ............................................................................................................................ 2 Module VIII ......................................................................................................................... 2 Networking......................................................................................................................... 2 Module IX........................................................................................................................... 2 Developing Android Services......................................................................................... 2 Module X............................................................................................................................ 2 Audio and Video................................................................................................................ 2
  • 4. SETUP Prepare your computer – Install SDK: Windows, Mac, Linux We assumeyou have already installed the Java JDK and EclipseIDEin your computer • Java JDK is availableat: http://www.oracle.com/technetwork/java/javase/downloads/index.html • EclipseIDEfor Java EE Developers is availableat: http://www.eclipse.org/downloads/ The next instructions aregiven to: (a) User Wanting to Update their Older Android Workbench, (b) FirstTime Users. SETUP (a) Users Wanting to Update an Older Android Workbench If you are currently using the Android SDK, you justneed to update to the latest tools or platformusing the already installed Android SDK and AVD Manager. 1. Click onthe SDK Manager icon. 2. You will see a formsimilar to the one onthe right. 3. Select the Packages you want to installandwait until theyare setupin your machine.
  • 5. SETUP (b) First Time Users (Windows, Mac, Linux) 1. InstalltheappropriateSDK starter package fromthepage http://developer.android.com/sdk/index.html 2. InstalltheADT Plugin for Eclipse 1. StartEclipse,then selectHelp > Install New Software.... 2. ClickAdd button (top‐rightcorner) 3. In thenextdialog‐boxenter "ADT Plugin" for the Nameand thefollowing URL for theLocation:https://dl‐ssl.google.com/android/eclipse/ 4. ClickOK 5. Selectthecheckbox nextto DeveloperTools and click Next > Next 6. Acceptthelicenseagreements,then click Finish. 7. After theinstallation end you need to restartEclipse. 3. Add Android platforms and other components to yourSDK (seeprevious option (a) ) Configuring the ADT Plugin The next step is to modify your ADT preferences in Eclipseto pointto the Android SDK directory: 1. Select Window > Preferences... to open the Preferences panel (Mac OS X: Eclipse > Preferences). 1. Select Android from the left panel. 2. To set the box SDK Location that appears in the main panel, click Browse... and locateyour downloaded SDK directory ( usually c:/ProgramFiles (x86)/Android /android‐sdk ) 3. Click Apply, then OK. Done
  • 6. Selecting an Android Virtual Device (AVD) You should testyour applications on a real phone (or tablet). However, the SDK allows you to create realistic virtual devices on which your applications can betested. Creating an Android Virtual Device (AVD) An AVD allows you to simulated devices and SDKs. To create a virtual unitfollowthe next steps: 1. Click onthe AVDManager 2. Click New. The Create New AVD dialog appears. 3. Type the name ofthe AVD, such as “18‐JellyBean" 4. Choose a target (suchas “Google APIs…API Level18”). 5. Indicate howmuchmemorythe simulator will use. 6. Tick option box “Snapshot” to loadfaster. 7. Indicate screensize (HVGA is sufficient ingeneral) 8. Optionallyspecifyanyadditional hardware components (such as SD‐card, camera,…) 9. Click Create AVD.
  • 8. LifeCycle App EXAMPLE: LifeCycle app The following application demonstrates the transitioning of a simple activity through the Android’s sequence of Life‐Cycle states. 1. A Toast‐msgwill bedisplayed showing the currentevent’s name. 2. An EditText box is provided for the user to indicatea background color. 3. When the activity is paused theselected background color valueis saved to a SharedPreferences container. 4. When the application is re‐executed the lastchoiceof background color should be applied. 5. An EXIT button should be provideto terminate the app. 6. You areasked to observe the sequence of messages when the application: 1. Loads for the firsttime 2. Is paused after clicking HOME button 3. Is re‐executed from launch‐pad 4. Is terminated by pressing BACK and its own EXIT button 5. Re‐executed after a background color is set Layout: atcivity_main.xml <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/myScreen1" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" tools:context=".MainActivity" > <EditText android:id="@+id/editText1" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Pick background (red, green, blue, white)" android:ems="10" > <requestFocus /> </EditText> <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Exit" /> <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text=" spy box ‐ try clicking HOME and BACK" /> </LinearLayout> 33 LifeCycle App (1) 34
  • 9. LifeCycle App (2) package csu.matos.lifecycle; import java.util.Locale; . . . //other libraries omitted for brevity public class MainActivity extends Activity { //class variables private Context context; private int duration = Toast.LENGTH_SHORT; //Matching GUI controls to Java objects private Button btnExit; private EditText txtColorSelected; private TextView txtSpyBox; private LinearLayout myScreen; private String PREFNAME = "myPrefFile1"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //display the main screen setContentView(R.layout.activity_main); //wiring GUI controls and matching Java objects txtColorSelected = (EditText)findViewById(R.id.editText1); btnExit = (Button) findViewById(R.id.button1); txtSpyBox = (TextView)findViewById(R.id.textView1); myScreen = (LinearLayout)findViewById(R.id.myScreen1); 3) //set GUI listeners, watchers,... btnExit.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { finish(); } }); //observe (text) changes made to EditText box (color selection) txtColorSelected.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { // nothing TODO, needed by interface } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { // nothing TODO, needed by interface } @Override public void afterTextChanged(Editable s) { //set background to selected color String chosenColor = s.toString().toLowerCase(Locale.US); txtSpyBox.setText(chosenColor); setBackgroundColor(chosenColor, myScreen); } }); 36
  • 10. LifeCycle App (4) //show the current state's name context = getApplicationContext(); Toast.makeText(context, "onCreate", duration).show(); } //onCreate @Override protected void onDestroy() { super.onDestroy(); Toast.makeText(context, "onDestroy", duration).show(); } @Override protected void onPause() { super.onPause(); //save state data (background color) for future use String chosenColor = txtSpyBox.getText().toString(); saveStateData(chosenColor); Toast.makeText(context, "onPause", duration).show(); } @Override protected void onRestart() { super.onRestart(); Toast.makeText(context, "onRestart", duration).show(); } LifeCycle App (5) @Override protected void onResume() { super.onResume(); Toast.makeText(context, "onResume", duration).show(); } @Override protected void onStart() { super.onStart(); //if appropriate, change background color to chosen value updateMeUsingSavedStateData(); Toast.makeText(context, "onStart", duration).show(); } @Override protected void onStop() { super.onStop(); Toast.makeText(context, "onStop", duration).show(); }
  • 11. LifeCycle App (6) private void setBackgroundColor(String chosenColor, LinearLayout myScreen) { //hex color codes: 0xAARRGGBB AA:transp, RR red, GG green, BB blue if (chosenColor.contains("red")) myScreen.setBackgroundColor(0xffff0000); //Color.RED if (chosenColor.contains("green")) myScreen.setBackgroundColor(0xff00ff00); //Color.GREEN if (chosenColor.contains("blue")) myScreen.setBackgroundColor(0xff0000ff); //Color.BLUE if (chosenColor.contains("white")) myScreen.setBackgroundColor(0xffffffff); //Color.BLUE } //setBackgroundColor private void saveStateData(String chosenColor) { //this is a little <key,value> table permanently kept in memory SharedPreferences myPrefContainer = getSharedPreferences(PREFNAME, Activity.MODE_PRIVATE); //pair <key,value> to be stored represents our 'important' data SharedPreferences.Editor myPrefEditor = myPrefContainer.edit(); String key = "chosenBackgroundColor"; String value = txtSpyBox.getText().toString(); myPrefEditor.putString(key, value); myPrefEditor.commit(); }//saveStateData LifeCycle App (7) private void updateMeUsingSavedStateData() { // (in case it exists) use saved data telling backg color SharedPreferences myPrefContainer = getSharedPreferences(PREFNAME, Activity.MODE_PRIVATE); String key = "chosenBackgroundColor"; String defaultValue = "white"; if (( myPrefContainer != null ) && myPrefContainer.contains(key)){ String color = myPrefContainer.getString(key, defaultValue); setBackgroundColor(color, myScreen); } }//updateMeUsingSavedStateData } //Activity
  • 13. The app is re‐executed LifeCycle App (10) Saved stateinformation defining background color is reusedby the new app’s instance. Lifecyclebegins on the onCreate state User selects a green background andclicks Exit. When the appis pausedthe user’s selectionis savedand the app finallyterminates. 43 The app is re‐executed LifeCycle App (11) The app is re‐startedand becomes visibleagain,showing all thestate values previouslyset by theuser (see the text boxes) User selects a green background andclicks the HOME key. Whentheapp is paused theuser’s selection is saved,theapp is still active but it is not visible.
  • 15. Basic Widgets: Labels <?xml version="1.0" encoding="utf‐8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/widget32" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <TextView android:id="@+id/txt1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="#ffffff00" android:inputType="none" android:text="@string/long_msg_1" android:textSize="20sp" /> </LinearLayout> Hint on Better Programming Style: Add to the res/values/stringg.xml the entry <string name=“long_msg_1">Line1of longmessagenLine2 of long msgn...nlastline</string> EditText Caution WARNING This text field does not specify an InputType or a hint is justa warning requesting your help to improve the working of a TextView. Add the clause android:hint=“…some hint here…” and/or android:InputType=“…choice…” where choices are
  • 16. a Basic Widgets: Buttons • A Button widget allows thesimulation of a clicking action on a GUI. • Button is a subclass of TextView. Therefore formatting button’s face is similar to the setting of a TextView. <Button android:id="@+id/ Basic Widgets: Images • ImageView and ImageButton are two Android widgets that allowembedding of images in your applications. • Analogue to TextView and Button controls (respectively). • Each widget takes an android:src or android:background attribute (in an XML layout) to specify what pictureto use. • Pictures areusually stored in the res/drawable folder (optionallya low,medium, and high definition version of the same image could be stored to later be used with differenttypes of screens)
  • 17. = "@string/click me" Basic Widgets: Images <LinearLayout . . . <ImageButton android:id="@+id/myImageBtn1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/ic_launcher" > </ImageButton> <ImageView android:id="@+id/myImageView1" android:layout_width="150dp" android:layout_height="120dp" android:scaleType "fitXY" android:src="@drawable/flower1" > </ImageView> </LinearLayout> This is a jpg, gif, png,…file Basic Widgets: Combining Images & Text A common Button could display textand a simpleimageas shown below <LinearLayout . . . <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:drawableLeft="@drawable/ic_happy_face" android:gravity="left|center_vertical" android:padding="15dp" android:text= @string/click_me /> </LinearLayout>
  • 18. Basic Widgets: Images Icons are small images used to graphically representyour application and/or parts of it. They may appear in different places of the device including: • Home screen • Launcher window. • Options menu • Action Bar • Status bar • Multi‐tab interface. • Pop‐up dialog boxes • List view Detailed information at: http://developer.android.com/guide/practices/ui_guidelines/icon_design.html HINT Several websites allowyou to convert your pictures to image files under a variety of formats & sizes (.png, .jpg, .gif, etc). For instancetry: http://www.prodraw.net/favicon/index.php http://converticon.com/ 59 Basic Widgets: EditText • The EditText (ortextBox) widgetis an extension of TextView that allowsuser’sinput. • The control candisplay editable text(usesHTML‐styles:bold, ... ). • ImportantJavamethods are: txtBox.setText(“someValue”) and txtBox.getText().toString()
  • 19. Basic Widgets: EditText • The EditText (ortextBox) widgetis an extension of TextView that allowsuser’sinput. • ImportantJavaI/Omethods are: txtBox.setText(“someValue”) and txtBox.getText().toString() • The control candisplay editableor HTML‐formatted textbymeansof Html.fromHtml(text) Basic Widgets: EditText CAUTION: Deprecated Methods • android:autoText • android:capitalize • android:digits • android:singleLine • android:password • android:numeric • android:phonenumber Instead use the newer atttribute: android:inputType=“…choices…” where choices include
  • 20. Basic Widgets: EditViews Example ... <EditText android:id="@+id/txtUserName" android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="textCapWords|textAutoCorrect" Enter “teh” It will be changed to: “the” Each wordis android:hint="@string/enter_your_first_and_last_name" capitalized android:textSize="18sp" /> ... Suggestion (greyout) Example: Login Screen In this examplewe will createand use a simplelogin screen holding a label( TexView), a textBox (EditText), and a Button. A fragment of its functionality isshown below. Hint Capitals & spelling Setting text A brief message box
  • 21. "1 Example: Login Screen Layout Design 1 of 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#886495ed" android:orientation="vertical" android:padding="2dp" > <TextView android:id="@+id/textView1" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="1dp" android:background="#ffffff00" android:text="@string/ACME_Corp_Caption" /> <EditText android:id="@+id/txtUserName" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="1dp" android:hint="@string/Enter_your_First_and_Last_name" android:inputType="textCapWords|textAutoCorrect" android:textSize="18sp" > <requestFocus /> </EditText> 65 Example: Login Screen Layout Design 2of 2 <Button android:id="@+id/button1" android:layout_width="82dp" android:layout_height="wrap_content" android:layout_marginTop="1dp" android:text="@string/login" /> </LinearLayout> Resource Captions: res/values/strings <?xml version= 1.00" encoding="utf‐8"?> <!‐‐ this is the res/values/strings.xml file ‐‐> <resources> <string name="app_name">GuiDemo</string> <string name="action_settings">Settings</string> <string name="login">login</string> <string name="ACME_Corp_Caption">login</string> <string name="Enter_your_First_and_Last_name">Enter your First and Last name</string> </resources>
  • 22. Example: Login Screen Rendering the Layout The images belowshowthe previouslydefined loginscreendisplayed bytwo different devices running SDK2.3 (Gingerbread)andSDK4.3 (Ice Cream) GingerBread SDK Ice Cream SDK 67 Example: Login Screen MainActivity.java Class (1 of 2) package csu.matos.g uidem o; import ... // "LOGIN" ‐ a gentle introduction to UI controls public class MainActivi ty extend s Activity { //class variables representing UI controls to be controlled from the program TextView labelUserName; EditText txtUserName; Button btnBegin; //variables used with the Toast message class private Context context; private int duration = Toast.LENG TH_SHO RT; @Override public void onCreate(Bu ndle savedIn stanc eState ) { super.on Create (save dInsta nceSt ate); //show the login screen setContentView(R.layout.activity_main); context = getApplicationContext();
  • 23. Example: Login Screen MainActivity.java Class (2 of 2) //binding the UI's controls defined in "main.xml" to Java code labelUserName = (TextView) findViewById(R.id.textView1); txtUserName = (EditText) findViewById(R.id.txtUserName); btnBegin = (Button) findViewById(R.id.button1); //LISTENER: allowing the button widget to react to user interaction btnBegin.setOnClickListener(ne w OnClickL istene r() { @Override public void onClick(Vie w v) { String userName = txtUserName.getText().toString(); if (userName. compar eTo("M aria Macare na")== 0){ labelUserName.setText("OK, please wait..."); Toast.makeText(context, "Bienvenido " + userName, duration).show(); } Toast.makeText(context, userName + " is not a valid USER" , duration).show(); } });// onClick }//onCreate }//class Your turn! Implement any/all of the following projects Usingsimpletext boxes (EditText, TextView) and buttons: 1. Currency calculator 2. Tip Calculator 3. Simple Flashlight
  • 24. Common Layouts FrameLayout • FrameLayout is the simplesttype of GUI container. • Useful as outermost container holding a window. • Allows you to define how much of the screen (high, width) is to be used. • All its children elements arealigned to the top left corner of the screen.; The Linear Layout 1. Linear Layout • The LinearLayout supports a filling strategy in which new elements are stacked either in a horizontal or vertical fashion. • If the layouthas a vertical orientation newrows areplaced one on top of the other. • A horizontal layoutuses a side‐by‐sidecolumn placement policy.
  • 25. property can be set to: "wrap content" The Linear Layout 1. LinearLayout: Setting Attributes Configuring a LinearLayout usually requires you to set the following attributes: • orientation (vertical, horizontal) • fill model (match_parent, wrap_contents) • weight (0, 1, 2, …n ) • gravity (top, bottom, center,…) • padding ( dp – dev. independentpixels) • margin ( dp – dev. independentpixels) The LinearLayout ‐ Orientation<LinearLayout 1.1 Attribute: Orientation The android:orientation horizontal horizontal for columns, or vertical for rows. Use setOrientation() for runtime changes. v e r t i c a l xmlns:android="http://schemas.android.com/ap k/res/android" android:id="@+id/myLinearLayout" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal" android:padding="4dp" > <TextView android:id="@+id/labelUserName" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="#ffff0000" android:text=" User Name " android:textColor="#ffffffff" android:textSize="16sp" android:textStyle="bold" /> <EditText android:id="@+id/ediName" android:layout_width="wrap_content" android:layout_height= wrap_content android:text="Maria Macarena" android:textSize="18sp" /> <Button android:id="@+id/btnGo" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Go" android:textStyle="bold" /> </LinearLayout> 20
  • 26. The LinearLayout – Fill Model 1.2 Fill Model • Widgets have a "natural size“based on their included text (rubber band effect). • On occasions you may want your widget to have a specific spaceallocation (height, width) even if no text is initially provided (as isthe caseof the empty text box shown below). natural sizes empty screen space The LinearLayout – Fill Model 1.2 Fill Model All widgets insidea LinearLayoutmust include‘width’ and ‘height’ attributes. android:layout_width android:layout_height Values used in defining height and width can be: 1. A specific dimension such as125dp (device independent pixels,a.k.a.dip ) 2. wrap_content indicates the widget should justfill up its natural space. 3. match_parent (previously called ‘fill_parent’) indicates thewidget wants to be as bigas the enclosing parent.
  • 27. space The LinearLayout – Fill Model <?xml version="1.0" encoding="utf‐8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 1.2 Fill Model 125 dp entire row (320 dp on medium resol uti on scree ns) android:id="@+id/myLinearLayout" android:layout_width="match_parent " android:layout_height="match_parent " android:background="#ff0033cc" android:orientation="vertical" android:padding="4dp" > <TextView android:id="@+id/labelUserName" android:layout_width="_parent" android:layout_height="wrap_content " android:background="#ffff0066" android:text="User Name" android:textColor="#ff000000" android:textSize="16sp" android:textStyle="bold" /> <EditText android:id="@+id/ediName" android:layout_width="match_parent " android:layout_height="wrap_content " android:textSize="18sp" /> <Button android:id="@+id/btnGo" android:layout_width="125dp" android:layout_height="wrap_content " android:text="Go" android:textStyle="bold" /> Row‐wise Use all the row Specific size: 125dp . </LinearLayout> The LinearLayout – Weight 1.2 Weight Indicates howmuch of the extra spacein the LinearLayout will beallocated to the view. Use 0 if the view should not be stretched. The bigger the weight the larger the extra given to that widget. Example The XML specification for this windowis similar to the previous example. The TextViewandButtoncontrols have the additional property android:layout_weight="1" whereas the EditText control has android:layout_weight="2" Default value is 0 Takes: 2 /(1+1+2) of the screen space 24
  • 28. The LinearLayout – Gravity 1.3 Layout_Gravity • It is used to indicatehowa control will align on the screen. • By default, widgets are left‐ and top‐aligned. • You may use the XML property android:layout_gravity="…" to set other possiblearrangements: left, center, right, top, bottom, etc. Button has right layout_gravity The LinearLayout – Gravity 1.3 CAUTION: gravity vs. layout_gravity The difference between: android:gravity indicates howto placean object within a container.In the example the text is centered android:gravity="center" android:layout_gravity positions theview with respect to its android:layout_gravity="center"
  • 29. at The LinearLayout – Padding 1.4 Padding • The padding attribute specifies the widget’s internal margin (in dp units). • The internal margin is theextra spacebetween the borders of the widget's "cell"and the actual widget contents. • Either use • android:padding property • or call method setPadding() runtime. The LinearLayout – Padding 1.3 Padding and Marging
  • 30. The LinearLayout – Padding 1.3 Internal Margins Using Padding Example: The EditText box has been changed to display 30dp of padding all around <EditText android:id="@+id/ediName" android:layout_width="match_parent" android:layout_height="wrap_content" android:textSize="18sp" androi d:pa ddin g="3 0dp" /> ... The LinearLayout – Margin 1.4 (External) Margin • Widgets –by default– are tightly packed next to each other. • To increasespacebetween them use the android:layout_margin attribute Increased inter‐widget space <EditText android:id="@+id/ediName" android:layout_width="match_parent" android:layout_height="wrap_content" android:textSize="18sp" andro id:l ayou t_ma rgin ="6d p" > </EditText> ...
  • 31. The Relative Layout 2. Relative Layout The placement of widgets in a RelativeLayout is based on their positional relationship to other widgets in the container and the parent container. A Example: A is bythe parent’s top C is below A, to its right B is below A, to the left o B C The Relative Layout 2. Example: Relative Layout Locationof the buttonis expressed in reference to its relative position with respect to the EditTextbox.
  • 32. The Relative Layout 2. Referring to the container Below there is a listof some positioning XMLboolean properties (=“true/false”) useful for collocating a widgetbased on the location of its parent container. android:layout_alignParentTop android:layout_alignParentBottom android:layout_alignParentLeft android:layout_alignParentRight android:layout_centerInParent android:layout_centerVertical android:layout_centerHorizontal The Relative Layout 2. Referring to other widgets The following properties managethe positioning of a widget respect to other widgets: android:layout_above=“@+id/wid1” android:layout_below android:layout_toLeftOf android:layout_toRightOf In this example widget “wid2” is map relative to wid1 (knownas “@+id/wid1” ) wid2 wid1 wid2
  • 33. only to The Relative Layout 2. Referring to other widgets – cont. android:layout_alignTop=“@+id/wid1” wid1 wid2 android:layout_alignBottom =“@+id/wid1” android:layout_alignLeft=“@+id/wid1” android:layout_alignRight=“@+id/wid1” wid1 wid1 wid2 wid2 wid1 wid2 The Relative Layout 2. Referring to other widgets When using relativepositioning you need to: 1. Use identifiers ( android:id attributes ) on all elements that you will be referring to. 2. XML elements arenamed using the prefix:@+id/... For instancean EditText box could be called: android:id="@+id/txtUserName" 3. You must refer l widgets that havebeen already defined.For instancea new control to be positioned below the txtUserName EditText box could refer to it using: android:layout_below="@+id/txtUserName"
  • 34. The Relative Layout 2. Example <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/myRelativeLayout" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#ff000099" > <TextView android:id="@+id/lblUserName" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" android:background="#ffff0066" android:text="User Name" android:textColor="#ff000000" android:textStyle="bold" > </TextView> <EditText android:id="@+id/txtUserName" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_below="@+id/lblUserName" android:padding="20dp" > </EditText> <Button android:id="@+id/btnGo" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignRight="@+id/txtUserName" android:layout_below="@+id/txtUserName" android:text="Go" android:textStyle="bold" > </Button> <Button android:id="@+id/btnCancel" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/txtUserName" android:layout_toLeftOf="@+id/btnGo" android:text="Cancel" android:textStyle="bold" > </Button> </RelativeLayout> The Table Layout 37 3. Table Layout 1. Android's TableLayout uses a grid to position your widgets. 2. Like in a matrix,cells in thegrid are identifiableby rows and columns. 3. Columns are flexible,they could shrink or stretch to accommodatetheir contents. 4. The element TableRow is used to define a new row in which widgets can be allocated. 5. The number of columns in a TableRowis determined by the total of side‐by‐ sidewidgets placed on the row.
  • 35. Basic XML Layouts ‐ Containers 3. Table Layout – Setting Number of Columns The number of columns in a row is determined by Android. Example: If your TableLayouthavethree rows,one with two widgets, one with three widgets, and one with four widgets, there will beatleastfour columns. 0 1 0 1 2 0 1 2 3 Basic XML Layouts ‐ Containers 3. Table Layout – Stretching a Column • A singlewidget in a TableLayoutcan occupy more than one column. • The android:layout_span property indicates thenumber of columns the widget is allowed to expand. <TableRow> <TextView android:text="URL:" /> <EditText android:id="@+id/entry" android:layout_span="3" /> </TableRow>
  • 37.
  • 38. Google Maps Android API V2 Tutorial – Hello GoogleMap Based on: https://developers.google.com/maps/documentation/android/start • We'll createa simpleActivity that shows a simplemap. • The map displays two markers:one represents a location in Cleveland Ohio,and the other is on San Jose Costa Rica. • The markers areconnected by a straightline. 7 Tutorial – HelloGoogleMap Based on: https://developers.google.com/maps/documentation/android/start Part 1. One Time Operation – Prepare your Eclipse Workspace • Select File > Import > Android > Existing Android Code Into Workspace and click Next. • Select Browse..., enter <android-sdk-folder>/extras/google/google_play_services/ libproject/google-play-services_lib, and clickFinish.
  • 39. Google Maps Android API V2 Tutorial – HelloGoogleMap Based on: https://developers.google.com/maps/documentation/android/start Part 1. One Time Operation – Prepare your Eclipse Workspace • After completing previous steps your workspaceshould includea new project called google-play-services_lib. 9 Google Maps Android API V2 Tutorial – HelloGoogleMap Based on: https://developers.google.com/maps/documentation/android/start Part 2. Creating the App 1. Create a newAndroid project, callit:HelloGoogleMap (minimum level API 11). 2. To establish a dependency between your Projectand Google Play Services, do this (starting on the Eclipse’s toolbar): Project > Properties> Android > Library> Add > google-play-services_lib
  • 40. Google Maps Android API V2 Tutorial – HelloGoogleMap Based on: https://developers.google.com/maps/documentation/android/start Part 2. Creating the App 3. Check that anupdated Google_Play_Services lib isavailable onthe device (you will need a ‘real’ workingdevice for testing, at this time the Emulator does not support GMS mapping). Add the following statements to your onCreate(…) method int result = GooglePlayServicesUtil .isGooglePlayServicesAvailable( getApplicationContext()); if ( result != ConnectionResult.SUCCESS ) { GooglePlayServicesUtil .getErrorDialog(result, MainActivity.this, 1).show(); } 11 Google Maps Android API V2 Tutorial – HelloGoogleMap Based on: https://developers.google.com/maps/documentation/android/start Part 2. Creating the App 4. Update your layout res/layout/activity_main.xml. Replace its contents with: <fragment xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/map" android:layout_width="match_parent" android:layout_height="match_parent" class="com.google.android.gms.maps.MapFragment" />
  • 41. Google Maps Android API V2 Tutorial – HelloGoogleMap Based on: https://developers.google.com/maps/documentation/android/start Part 2. Creating the App 5. The @+id/map entry defined in the previous XML definition is programmatically controlled through the GoogleMap map class level variable.Add the following statementto your onCreate method. map = ((MapFragment) getFragmentManager() .findFragmentById(R.id.map)) .getMap(); 6. Add the following lines into your AndroidManifest.xml (insertthem before the first<Activity>tag) <meta-data android:name="com.google.android.maps.v2.API_KEY" android:value="Your-40-chars-API-KEY-goes-here" /> Google Maps Android API V2 Tutorial – HelloGoogleMap Based on: https://developers.google.com/maps/documentation/android/start Part 2. Creating the App 7. Modify the app’s AndroidManifest.xml filewith the following permissions and features requests <uses-feature android:glEsVersion="0x00020000" android:required="true" /> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" /> <uses-permission android:name="YOUR_PACKAGE_NAME.permission.MAPS_RECEIVE" /> <permission android:name="YOUR_PACKAGE_NAME.permission.MAPS_RECEIVE" android:protectionLevel="signature" />
  • 42. Google Maps Android API V2 Tutorial – HelloGoogleMap Based on: https://developers.google.com/maps/documentation/android/start Part 2. Creating the App 8. Testyour app. It shouldshowa mapof the world centeredoncoordinates 00 ,00 (Atlantic Ocean, west of Africa) 9. Attribution Requirements. “… you must include the Google PlayServices attribution text as part of a "LegalNotices" section inyour application. Includinglegal notices as anindependent menu item, or as part of an "About" menu item, is recommended. The attribution text is available bymaking a call to “ GooglePlayServicesUtil.getOpenSourceSoftwareLicenseInfo(context); Google Maps Android API V2 Tutorial – HelloGoogleMap Based on: https://developers.google.com/maps/documentation/android/start Part 3. Improving the App – Adding a Marker 10. Modifyyour onCreate method. Adda callto the setUpMap method givenbelow private void setUpMap () { // test that we have a map already instantiated if (map == null) { map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap(); // Check if we were successful in obtaining the map. if (map != null) { // now it is now safe to manipulate the map. map.setMapType(GoogleMap.MAP_TYPE_NORMAL); // disable indoor maps map.setIndoorEnabled(false); // this point represents location of Cleveland State University LatLng CSU_OHIO = new LatLng(41.501936, -81.675278); Marker csu_ohio_marker = map.addMarker(new MarkerOptions() .position(CSU_OHIO) .title("Cleveland State University") .snippet("Cleveland, Ohio") ); map.moveCamera(CameraUpdateFactory.newLatLngZoom( CSU_OHIO, 15.0f )); 16
  • 43. Google Maps Android API V2 Tutorial – HelloGoogleMap Based on: https://developers.google.com/maps/documentation/android/start Part 3. Improving the App – Adding a Marker 10. Continuation - setUpMap method: // set up map UI settings: UiSettings mapUI = map.getUiSettings(); // enable: pan, zoom, tilt, rotate mapUI.setAllGesturesEnabled(true); // enable compass mapUI.setCompassEnabled(true); // enable zoom controls mapUI.setZoomControlsEnabled(true); } } }// setUpMapIfNeeded 17 Google Maps Android API V2 Tutorial – HelloGoogleMap Based on: https://developers.google.com/maps/documentation/android/start Part 4. Improving the App – Adding PolyLines 11. Modifythe setUpMap method introduced inthe previous section. Replace the statement map.movecamera... with the following next lines // this marker represents Universidad de Costa Rica LatLng SANJOSE1_CR = new LatLng(9.937931, -84.051936); Marker san_jose1_marker = map.addMarker(new MarkerOptions() .position(SANJOSE1_CR) .title("Universidad de Costa Rica") .snippet("San Jose, CR") .icon(BitmapDescriptorFactory.defaultMarker( BitmapDescriptorFactory.HUE_GREEN)) ); // drawing a straight line between the two points Polyline line = map.addPolyline(new PolylineOptions() .add( SANJOSE1_CR, CSU_OHIO ) .width(2) .color(Color.BLUE)); // this point is halfway between Cleveland and San Jose LatLng halfWay = new LatLng( (SANJOSE1_CR.latitude + CSU_OHIO.latitude)/2, (SANJOSE1_CR.longitude + CSU_OHIO.longitude)/2 ); map.moveCamera( CameraUpdateFactory.newLatLngZoom( halfWay, 4.0f ) );
  • 44. Tutorial – HelloGoogleMap Based on: https://developers.google.com/maps/documentation/android/start Part 4. Improving the App – Adding PolyLines 12. Test your application.
  • 46. Creating a Bluetooth client socket priva t e void connectT oSer verS ocket( Bl uet oothD evic e devi c e, UUID uuid) { try{ BluetoothS ocket client S oc ke t = device.crea teRf c om mS ocket T oSe r vi ceRe c or d(u ui d); // Block until server connection accepte d. clientSocket.connect(); // Start listening for messages. listenF or M es s a ges ( c li e n t S oc ke t ); // Add a reference to the socket used to send messages. transfe rS o ck et = clientSocket; } catch (IOExcept i on e) { Log.e(“BLU ETOO TH”, “Bluet oot h client I/O Except i on ”, e); } } Sending and receiving strings using Bluetooth Sockets priva t e void listenFor Me ssa ges( Bl u et ooth S ocke t socket , Strin gB u il d e r incoming) { listening = true; int buffer S i z e = 1024; byte[] buffe r = new byte[bufferSize]; try { InputStream instream = socket. ge t In pu t S tr ea m () ; int bytesRead = -1; while (listening) { bytesRead = instr ea m . r e a d( bu f f e r) ; if (bytesRead != -1) { Strin g result = “”; while ((bytesRea d == bufferSize) && (buffer[bufferSize-1] != 0)){ result = result + new String(buffer, 0, bytesRead - 1); bytesRead = instr ea m . r e a d( bu f f e r) ; } result = result + new String(buffer, 0, bytesRead - 1); incom i n g. a ppe n d( r es u lt ); } socket.close(); } } catch (IOExcept i on e) { Log.e(TAG, “Message receive d failed.”, e); } finally { } }
  • 47. Listening for NFC tags <activity android:name= ”.B logVi ewer ”> <intent-filter> <action android:name= ”a ndroid. nfc.ac ti on. NDEF_DISCO VERED”/> <category android:na me = ”an dr oi d.i nte nt. cat e gor y.DEFA U LT ”/ > <data android:sch eme = ”htt p” androi d: h os t = ”bl o g. ra di oa ct i ve ya k. c om ”/ > </intent-filter> </acti vi t y> Extracting NFC tag payloads Strin g action = getIntent().getAction(); if (NfcAdapter.ACTION_ NDEF_DISC OVERED.equals(acti on)) { Parcelable[] messages = intent.getP ar cel a ble Ar ra yE xtr a(Nf c A da pte r.E XT RA_ NDEF_ M ES SA GE S); for (int i = 0; i < messages.le n gth ; i++) { NdefMessage message = (NdefMessa ge) mes sa ges[ i]; NdefRecord[] records = message.ge tRe c or ds(); for (int j = 0; j < recor d s. l e n gt h ; j++) { NdefRecord record = records[j]; // TODO Process the individual recor ds . } } }
  • 49. + "n" Android Files Example 0: Reading a ResourceFile(see previous figure) //reading an embedded RAW data file public class File1Resources extends Activity { TextView txtMsg; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); txtMsg = (TextView) findViewById(R.id.textView1); try { PlayWithRawFiles(); } catch (IOException e) { txtMsg.setText( "Problems: " + e.getMessage() ); } }// onCreate 7 Android Files Example 1: Reading a ResourceFile(see previous figure) public void PlayWithRawFiles() throws IOException { String str=""; StringBuffer buf = new StringBuffer(); int fileResourceId = R.raw.my_text_file; InputStream is = this.getResources().openRawResource(fileResourceId); BufferedReader reader = new BufferedReader(new InputStreamReader(is)); if (is!=null) { while ((str = reader.readLine()) != null) { buf.append(str ); } } is.close(); txtMsg.setText( buf.toString() ); }// PlayWithRawFiles } // File1Resources 8
  • 50. Android Files Example 2: (Internal Storage ) Read/Write an Internal File. In this example an application collects data from the UI and saves itto a persistentdata fileinto the (limited) internal Android System spacearea. Next time the application is executed the Resource File will beread and its data shown on the UI 9 Android Files Example 2: (Internal Storage ) Read/Write an Internal File. The internal resource file is private and cannot be seen by other apps residing in main memory.
  • 51. Android Files Example2: Grab data from screen, save to file, retrieve from file. <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#ffdddddd" android:padding="10dp" android:orientation="vertical" > <Button android:id="@+id/btnFinish" android:layout_width="wrap_content" android:layout_height="wrap_content" android:padding="10dp" android:text=" Save File and Close " /> <EditText android:id="@+id/txtMsg" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="10dp" android:background="#ffffffff" android:gravity="top" android:hint="Enter some lines of data here..." /> </LinearLayout> 11 Android Files Example 2: Grab data from screen, saveto file, retrieve from file 1/3. public class File2WriteRead extends Activity { private final static String FILE_NAME = "notes.txt"; private EditText txtMsg; @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main); txtMsg = (EditText) findViewById(R.id.txtMsg); // deleteFile(); //keep for debugging Button btnFinish = (Button) findViewById(R.id.btnFinish); btnFinish.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { finish(); } }); }// onCreate
  • 52. "/data/data/cis470 filewriteread/files/" Android Files Example 2: Grab data from screen, saveto file, retrieve from file 2/3. public void onStart() { super.onStart(); try { InputStream inputStream = openFileInput(FILE_NAME); if (inputStream != null) { InputStreamReader inputStreamReader = new InputStreamReader(inputStream); BufferedReader reader = new BufferedReader(inputStreamReader); String str = "READING FROM EXISTING DISKn"; StringBuffer stringBuffer = new StringBuffer(); while ((str = reader.readLine()) != null) { stringBuffer.append(str + "n"); } inputStream.close(); txtMsg.setText(stringBuffer.toString()); } } catch (java.io.FileNotFoundException e) { } catch (Throwable t) { Toast.makeText(this, "Exception: " + t.toString(), 1).show(); } }// onStart 13 Android Files Example 2: Grab data from screen, saveto file, retrieve from file 3/3. public void onPause() { super.onPause(); try { OutputStreamWriter out = new OutputStreamWriter( openFileOutput(FILE_NAME, 0)); out.write(txtMsg.getText().toString()); out.close(); } catch (Throwable t) { txtMsg.setText( t.getMessage() ); } }// onPause private void deleteFile() { String path = /data/data/cis470.matos.filewriteread/files/ + FILE_NAME; File f1 = new File(path); Toast.makeText(getApplicationContext(), "Exists " + f1.exists() , 1).show(); boolean success = f1.delete(); if (!success){ Toast.makeText(getApplicationContext(), "Deletion failed.", 1).show(); }else{ Toast.makeText(getApplicationContext(), "OK. File deleted.", 1).show(); } } 14
  • 54. Example 1. Create a SQLite Database package cis70.matos.sqldatabases; public class SQLDemo1 extends Activity { SQLiteDatabase db; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); // this provides the 'real' path name to theexternal SD card String SDcardPath = Environment.getExternalStorageDirectory().getPath(); // For internal memory: "data/data/cis470.matos.sqldatabases/myfriendsDB" TextView txtMsg = (TextView)findViewById(R.id.txtMsg); String myDbPath = SDcardPath + "/" + "myfriends"; txtMsg.setText("DB Path: " + myDbPath); try { db = SQLiteDatabase.openDatabase(myDbPath, null, SQLiteDatabase.CREATE_IF_NECESSARY); // here you do something with your database ... db.close(); txtMsg.append("nAll done!"); } catch (SQLiteException e) { txtMsg.append( e.getMessage() ); } }//onCreate }//class 7 SQL Databases Example 1. Create a SQLite Database using Internal Memory Android’s System Image: /data/data/cis470.matos.sqldatabases/ myfriendsDB 8
  • 55. SQL Databases Example2 An alternative way of opening/creating a SQLITE database in your local Android’s data space is given below SQLiteDatabase db = this.openOrCreateDatabase( "myfriendsDB", MODE_PRIVATE, null); If this app is created in a namespace called “cis493.sql1”, the full nameof the newly created databasefilewill be: /data/data/cis493.sql1/databases/myfriendsDB This filecould later beused by other activities in theapp or exported out of the emulator (adb push…) and given to a tool such as SQLITE_ADMINISTRATOR (see notes at the end). SQL Databases Example2 An alternative way of opening/creating a SQLITE database in your local Android’s System Image is given below SQLiteDatabase db = this.openOrCreateDatabase( "myfriendsDB2", MODE_PRIVATE, null); Where: 1. “myFriendsDB2” is the abbreviated filepath.The prefix is assigned by Android as:/data/data/<app namespace>/databases/myFriendsDB2. 2. MODE could be: MODE_PRIVATE, MODE_WORLD_READABLE, and MODE_WORLD_WRITEABLE. Meaningful for apps consisting of multiples activities. 3. null refers to optional factory class parameter (skip for now)
  • 57. Consuming Web Services Example ‐ How .NET Web Services Are Called? Our examplecode consists of two fragments which implement the server and clientsideof the application. Server Side: • The document http://support.microsoft.com/kb/301273 describes howto create a simpleWeb servicerunning on a Windows IIS‐Server. Client Side: • We use the KSOAP 2.0 platformto request a sequence of remote procedure calls to the IIS server hosting our servicecode. • The methods includefunctions taking zero,or more arguments. • Arguments send/received can be simpledata types or complex objects. http://code.google.com/p/ksoap2‐android/ http://www.java2s.com/Code/Jar/k/Downloadksoap2base254jar.htm Consuming Web Services Example ‐ How .NET Web Services Are Called? KSOAP2 Documentation & Download http://code.google.com/p/ksoap2‐android/ http://code.google.com/p/ksoap2‐android/source/browse/m2‐ repo/com/google/code/ksoap2‐android/ksoap2‐android‐assembly/2.5.5/ http://www.java2s.com/Code/Jar/k/Downloadksoap2base254jar.htm Hosting Solution There are several options for externally hosting your .NET solution,registration strategy varies.Some Providers are: 1. http://www.asp.net/hosting 2. www.somee.com
  • 58. Consuming Web Services Example – TUTORIAL – IIS Server Side Code Services Available at the IIS Server Consuming Web Services Example – TUTORIAL – IIS Server Side Code Android App accessing all services available at the IIS server
  • 59. Consuming Web Services Example – TUTORIAL – Android Application Our Android app uses KSOAP 2 API. KSOAP is a webservice client library for constrained Java environments. SOAP protocol is widely used for machine‐ to‐machine interaction, it is strong‐typed and supports synchronous, asynchronous, and complex‐routing communication schemes. Our implementation includes three classes 1. Main webcalls areassembled 2. EnglishDistance (Serialized Class) 3. WebServiceCall deals with HTTP transporting of the request/response and envelope objects Consuming Web Services Example – TUTORIAL – Android Application A fragmentof the Android Mainclassfollows public class Main extends Activity { public TextView txtMsg; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); txtMsg = (TextView)findViewById(R.id.txtMsg); WebServiceCall webServiceCall = new WebServiceCall(); // add two numbers - get int result int intResult = webServiceCall.AddService(11, 22); txtMsg.append( "nAdd RESULT= " + intResult ); } All the intelligentworkisdone bythe WebServiceCall class.
  • 60. Consuming Web Services Example – TUTORIAL – Android Application The WebServiceCall classnegotiates the transporting ofrequest/responseobjects as well as preparation of serialization of complex data elements ( 1/4 ) import org.ksoap2.SoapEnvelope; import org.ksoap2.serialization.SoapObject; import org.ksoap2.serialization.SoapSerializationEnvelope; import org.ksoap2.transport.HttpTransportSE; import android.util.Log; public class WebServiceCall { private static final String SOAP_ACTION = "http://tempuri1.org/"; private static final String NAMESPACE = "http://tempuri1.org/"; private static final String URL = "http://iamok.somee.com/MathService.asmx"; protected Object call( String soapAction, SoapSerializationEnvelope envelope) { Consuming Web Services Example – TUTORIAL – Android Application WebServiceCall class (continuation 2/4) Object result = null; final HttpTransportSE transportSE = new HttpTransportSE(URL); transportSE.debug = false; // call and Parse Result. try { transportSE.call(soapAction, envelope); result = envelope.getResponse(); } catch (final Exception e) { Log.e("<<Exception>>",e.getMessage()); } return result; }
  • 61. Consuming Web Services Example 1 – TUTORIAL – Android Application Fragmentof the WebServiceCall class called to add twonumbers. Here input parameters and output valuesresultingfromthe webservice are sent andreceived. (cont. 3/4) public int AddService(int v1, int v2){ int intResult = 0; // indicate webservice (endpoint) to be called final String webMethod = "Add"; // Create the outgoing request message final SoapObject requestObject = new SoapObject(NAMESPACE, webMethod); // add outgoing parameters (name-type must agree with endpoint) requestObject.addProperty("v1", v1); requestObject.addProperty("v2", v2); // Create soap envelope for .NET server final SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11); envelope.dotNet = true; // place in envelope the outgoing request object envelope.setOutputSoapObject(requestObject); Consuming Web Services Example 1 – TUTORIAL – Android Application The WebServiceCall class (continuation 4/4) try { Web service is called here // call webmethod and parse returning response object final Object response = (Object) this.call( SOAP_ACTION + webMethod, envelope); if (response != null) intResult = Integer.parseInt(response.toString()); } catch (Exception e) { Log.e("<<Exception-Add>>",e.getMessage()); } return intResult; } }
  • 63. 1. Using Eclipse, create a new Android project and name it Services 2. Add a new Java Class file to the project and name it MyService. Populate the MyService.java file with the following code: package net.le a r n 2 de ve l o p.S e r vi c e s; import android.a pp.Se rv ice; import android.conte nt.I nte nt; import android.os.I Binder; import android.widget.Toas t; public class MyService extends Service { @Override public IBinder onBind(Intent arg0) { return null; } @Override public int onStartCommand(Intent intent, int flags, int startI d) { // We want this service to continue running until it is explicitly // stopped, so return sticky. Toast.makeText(th is , “Service Started”, Toast.LENGTH_LONG).s how (); return START_STICKY; } @Override public void onDestroy() { super.onDes troy(); Toast.makeText(th is , “Service Destroyed”, Toast.LENGTH_LONG).s ho w(); } } 3. In the An droidMan ifest.xml file, add the following statement in bold: <?xml version= ”1.0” encodin g=”utf-8”?> <manifest xmlns:androi d=”h tt p://s c he m as. an dr oi d. c om/a pk/r es/ an dr oi d” package=” n et . le a r n 2 de ve l op. Se r vi c e s ” android:versi onC ode = ”1 ” android:version Name= ”1.0” > <uses-sdk android:minSdkV ersi on = ”1 4 ” /> <appli ca ti o n android:i c on =”@ drawa ble/i c_ lau n c her ” androi d: la be l = ”@ string/app_name” > <activity androi d: la be l = ”@ string/app_name” android:name=”.ServicesActivity” > <intent-filter > <action android:name= ”a n dr oi d. i nt e n t.a c ti o n. M AIN ” /> <category android:name=”an dr oi d. in te nt. cat e gor y. L A UN CHER ” /> </intent-filter> </acti vi t y> <service android:name=”.MyService” /> </applica ti on > </manifest>
  • 64. 4. In the main .xml file, add the following statements in bold, replacing TextView : <?xml version= ”1.0” encodin g=”utf-8”?> <LinearLayout xmlns:androi d= ”ht t p:// s ch e ma s.a n dr oi d.c o m/a pk/ re s/a n dr oi d” android: la yout _wi dt h =”fill_parent” androi d:l a yout _h ei gh t = ”fill_parent” androi d: or ie n ta ti on = ”vertical” > <Button android:id= ”@+id/btnStartService” android:layout_w idth= ”fill_ pa re nt” android:layout_ height= ”w rap_content” android:text= ”Sta rt Service” android:onClick=”sta rtS e rv ice ”/> <Button android:id= ”@+id/btnStopService” android:layout_w idth= ”fill_ pa re nt” android:layout_ height= ”w rap_content” android:text= ”Stop Service” android:onClick=”stopSe rv ice ” /> </LinearLayout > 5. Add the following statements in bold to the ServicesActivity.java file: package net.le a r n 2 de ve l o p.S e r vi c e s; import android.app.Activity; import android.conte nt.I nte nt; import androi d. os. B u n dl e; import android.view .Vie w; public class ServicesActivity extends Activity { /** Called when the activity is first create d. */ @Override public void onCreate(Bundle savedIn st a n ce St at e) { super. on C r ea te (s a ve dIn st a n c eS t at e) ; setConte n tV ie w( R.l a you t. main); } public void startService(V ie w view) { startSe rv ice ( new Intent(getBase Conte xt(), MyService.clas s )); } public void stopService(View view) { stopService( new Intent(getBase Conte xt(), MyService.clas s )); } }
  • 65. 6. Press F11 to debug the application on the Android emulator. 7. Clicking the Start Service button will start the service. To stop the service, click the Stop Service button.
  • 67. MediaPlayer – Playing Audio from a Raw Resource <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/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="Humble Media Player" android:textStyle="bold"/> <Button android:id="@+id/playsong" android:layout_width="80px" android:layout_height="wrap_content" android:text="PLAY Music"/> <Button android:id="@+id/stopsong" android:layout_width="80px" android:layout_height="wrap_content" android:text="STOPMusic"/> </LinearLayout> //MyMediaPlayer Demo1: plays a song saved as a RAW resource //------------------------------------------------------------------------ package cis493.multimedia; import android.app.Activity; import android.os.Bundle; import android.media.MediaPlayer; import android.media.MediaPlayer.OnCompletionListener; import android.view.View; import android.widget.Button; import android.widget.Toast; public class MyMediaPlayer extends Activity { MediaPlayer mp; public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main); Button myPlayButton = (Button) findViewById(R.id.playsong);
  • 68. Button myPlayButton = (Button) findViewById(R.id.playsong); myPlayButton.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { try { mp = MediaPlayer.create(MyMediaPlayer.this, R.raw.beethoven_symphony_9); mp.start(); mp.setOnCompletionListener(new OnCompletionListener() { public void onCompletion(MediaPlayer arg0) { Toast.makeText(getApplicationContext(),"Br avo! Bravo!", 1).show(); } }); } catch (Exception e) { e.printStackTrace(); } } });// myPlayButton Button myStopButton = (Button) findViewById(R.id.stopsong); myStopButton.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { if (mp.isPlaying()) { mp.stop(); } }// onClick }); // myStopButton }// onCreate }