Android Programming
Labs
Complied by: Shady Selim
Table of ContentsModule I............................................................................................................................3Getting Started.................................................................................................................3Module II...........................................................................................................................7Activities, Fragments,.....................................................................................................7and Intents........................................................................................................................7Module III........................................................................................................................14Android User Interface..................................................................................................14Module IV........................................................................................................................36Sensors...........................................................................................................................36Module V.........................................................................................................................45Bluetooth, NFC, Networks, and...................................................................................45Wi-Fi................................................................................................................................45Module VI........................................................................................................................48I/O file..............................................................................................................................48Module VII.......................................................................................................................53Database.........................................................................................................................53Module VIII......................................................................................................................56Networking.....................................................................................................................56Module IX........................................................................................................................62Developing Android Services......................................................................................62Module X.........................................................................................................................66Audio and Video.............................................................................................................66
Module IGetting Started
SETUPPrepare your computer – Install SDK: Windows, Mac, Linux
We assume you have already installed the Java JDK and Eclipse IDE in your computer
• Java JDK is available at: http://www.oracle.com/technetwork/java/javase/downloads/index.html
• Eclipse IDE for Java EE Developers is available at: http://www.eclipse.org/downloads/
The next instructions are given to:(a) User Wanting to Update their Older Android Workbench, (b) First Time Users.
SETUP(a) Users Wanting to Update an Older Android WorkbenchIf you are currently using the Android SDK, you just need to update to the latest tools or platform using the already installed Android SDK and AVD Manager.
1. Click on the SDK Manager icon.
2. You will see a form similar to the one on the right.
3. Select the Packages you want to install and wait until they are setup in your machine.
SETUP(b) First Time Users (Windows, Mac, Linux)
1. Install the appropriate SDK starter package from the page http://developer.android.com/sdk/index.html
2. Install the ADT Plugin for Eclipse1. Start Eclipse, then select Help > Install New Software....2. Click Add button (top right‐ corner)3. In the next dialog‐box enter "ADT Plugin" for the Name and the following
URL for the Location: https://dl ssl.google.com/android/eclipse/‐4. Click OK5. Select the checkbox next to Developer Tools and click Next > Next6. Accept the license agreements, then click Finish. 7. After the installation end you need to restart Eclipse.
3. Add Android platforms and other components to your SDK (see previous option (a) )
Configuring the ADT Plugin
The next step is to modify your ADT preferences in Eclipse to point to 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 locate your downloaded SDK directory ( usually c:/Program Files (x86)/Android /android sdk‐ )
3. Click Apply, then OK.
Done
Selecting an Android Virtual Device (AVD)
You should test your applications on a real phone (or tablet). However, the SDK allows you to create realistic virtual devices on which your applications can be tested.
Creating an Android Virtual Device (AVD)
An AVD allows you to simulated devices and SDKs.To create a virtual unit follow the next steps:
1. Click on the AVD Manager2. Click New. The Create New AVD dialog appears.3. Type the name of the AVD, such as “18‐JellyBean"4. Choose a target (such as “Google APIs… API Level18”).5. Indicate how much memory the simulator will use.6. Tick option box “Snapshot” to load faster.7. Indicate screen size (HVGA is sufficient in general)8. Optionally specify any additional hardware components
(such as SD card,‐ camera, …)9. Click Create AVD.
LifeCycle App
EXAMPLE: LifeCycle appThe following application demonstrates the transitioning of a simple activity through the Android’s sequence of Life Cycle‐ states.1. A Toast‐msg will be displayed showing the current event’s name.2. An EditText box is provided for the user to indicate a background color.3. When the activity is paused the selected background color value is saved to
a SharedPreferences container.4. When the application is re‐executed the last choice of background color
should be applied.5. An EXIT button should be provide to terminate the app.6. You are asked to observe the sequence of messages when the application:
1. Loads for the first time2. Is paused after clicking HOME button3. Is re‐executed from launch pad‐4. Is terminated by pressing BACK and its own EXIT button5. Re‐executed after a background color is set
Layout: atcivity_main.xml<LinearLayoutxmlns: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" >
<EditTextandroid:i
d="@+id/editText1"android:layo
ut_width="match_parent"
android:layout_height="wrap_content"
android:hint="Pick background (red, green, blue, white)"
android:ems="10" >
<requestFocus />
</EditText>
<Buttonandroid:i
d="@+id/button1"android:layo
ut_width="wrap_content"
android:layout_height="wrap_content"
android:text="Exit" />
<TextView
Module IIActivities, Fragments, and Intents
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 variablesprivate Context context;private int duration = Toast.LENGTH_SHORT;//Matching GUI controls to Java objectsprivate Button btnExit;private EditText txtColorSelected;private TextView txtSpyBox;private LinearLayout myScreen;private String PREFNAME = "myPrefFile1";
@Overrideprotected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);//display the main screensetContentView(R.layout.activity_main);
//wiring GUI controls and matching Java objectstxtColorSelected = (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() {
@Overridepublic void onClick(View v) {
finish();}
});
//observe (text) changes made to EditText box (color selection) txtColorSelected.addTextChangedListener(new TextWatcher() {
@Overridepublic void onTextChanged(CharSequence s, int start, int before, int count) {
// nothing TODO, needed by interface}
@Overridepublic void beforeTextChanged(CharSequence s, int start, int count,
int after) {// nothing TODO, needed by interface
}@Overridepublic void afterTextChanged(Editable s) {
//set background to selected colorString chosenColor = s.toString().toLowerCase(Locale.US);txtSpyBox.setText(chosenColor);setBackgroundColor(chosenColor, myScreen);
}}); 36
LifeCycle App (4)
//show the current state's namecontext = getApplicationContext();Toast.makeText(context, "onCreate", duration).show();
} //onCreate
@Overrideprotected void onDestroy() {
super.onDestroy();Toast.makeText(context, "onDestroy", duration).show();
}
@Overrideprotected void onPause() {
super.onPause();//save state data (background color) for future useString chosenColor = txtSpyBox.getText().toString();saveStateData(chosenColor);
Toast.makeText(context, "onPause", duration).show();}
@Overrideprotected void onRestart() {
super.onRestart();Toast.makeText(context, "onRestart", duration).show();
}
LifeCycle App (5)
@Overrideprotected void onResume() {
super.onResume();Toast.makeText(context, "onResume", duration).show();
}
@Overrideprotected void onStart() {
super.onStart();//if appropriate, change background color to chosen valueupdateMeUsingSavedStateData();
Toast.makeText(context, "onStart", duration).show();}
@Overrideprotected 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 memorySharedPreferences myPrefContainer = getSharedPreferences(PREFNAME,
Activity.MODE_PRIVATE);//pair <key,value> to be stored represents our 'important' dataSharedPreferences.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 colorSharedPreferences 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 state information defining background color is reused by the new app’s instance. Life cycle begins on the onCreate state
User selects a greenbackground and clicks Exit. When the app is paused the user’s selection is saved and the app finally terminates. 43
The app is re‐executed
LifeCycle App (11)
The app is re started‐ and becomes visible again, showing all the state values previously set by the user (see the text boxes)
User selects a greenbackground and clicks the HOME key. When the app is paused the user’s selection is saved, the app is still active but it is not visible.
Module IIIAndroid 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" >
<TextViewandroid: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">Line1 of long message\nLine2 of long msg\n...\nlast line</string>
EditText CautionWARNING
This text field does not specify anInputType or a hint
is just a 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 the simulation of a clicking action on a GUI.
•Button is a subclass of TextView. Therefore forma
tting button’s face
is similar to the setting of a TextView.
<Buttonandroid:id="@+id/
Basic Widgets: Images• ImageView and ImageButton are two Android
widgets that allow embedding 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 picture to use.
• Pictures are usually stored in the res/drawable folder (optionally a low, medium, and high definition version of the same image could be stored to later be used with different types of screens)
=
"@string/click me"
Basic Widgets: Images<LinearLayout
. . .
<ImageButtonandroid:id="@+id/myImageBtn1"android:layout_width="wrap_content"android:layout_height="wrap_content"android:src="@drawable/ic_launcher" >
</ImageButton>
<ImageViewandroid: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 & TextA common Button could display text and a simple image as shown below
<LinearLayout. . .
<Buttonandroid: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: ImagesIcons are small images used to graphically represent your 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
HINTSeveral websites allow you to convert your pictures to image files under a variety of formats & sizes (.png, .jpg, .gif, etc). For instance try:http://www.prodraw.net/favicon/index.php http://converticon.com/ 59
Basic Widgets: EditText
• The EditText (or textBox) widget is an extension of TextView that allows user’s input.
• The control can display editable text (uses HTML styles:‐ bold, ... ).
• Important Java methods are:
txtBox.setText(“someValue”) and txtBox.getText().toString()
Basic Widgets: EditText
• The EditText (or textBox) widget is an extension of TextView that allows user’s input.
• Important Java I/O methods are:
txtBox.setText(“someValue”) and txtBox.getText().toString()
• The control can display editable or HTML‐formatted text by means of 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: EditViewsExample
...
<EditTextandroid: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 word is android:hint="@string/enter_your_first_and_last_name" capitalized
android:textSize="18sp" />
... Suggestion (grey out)
Example: Login ScreenIn this example we will create and use a simple login screen holding a label( TexView), a textBox (EditText), and a Button. A fragment of its functionality is shown below.
Hint Capitals & spelling
Setting text
"1
A brief message box
Example: Login ScreenLayout 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" >
<TextViewandroid: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" />
<EditTextandroid: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 ScreenLayout Design 2of 2
<Buttonandroid: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 ScreenRendering the LayoutThe images below show the previously defined login screen displayed by two different devices running SDK2.3 (Gingerbread) and SDK4.3 (Ice Cream)
GingerBread SDK Ice Cream SDK 67
Example: Login ScreenMainActivity.java Class (1 of 2)
package csu.matos.guidemo;import ...// "LOGIN" ‐ a gentle introduction to UI controls
public class MainActivity extends Activity {
//class variables representing UI controls to be controlled from the programTextView labelUserName;EditText txtUserName;Button btnBegin;
//variables used with the Toast message classprivate Context context;
private int duration = Toast.LENGTH_SHORT;
@Overridepublic void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);//show the login screensetContentView(R.layout.activity_main);context = getApplicationContext();
Example: Login ScreenMainActivity.java Class (2 of 2)
//binding the UI's controls defined in "main.xml" to Java codelabelUserName = (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 interactionbtnBegin.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {
String userName = txtUserName.getText().toString();if (userName.compareTo("Maria Macarena")==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 Using simple text boxes (EditText, TextView) and buttons:
1. Currency calculator 2. Tip Calculator3. Simple Flashlight
Common Layouts
FrameLayout
• FrameLayout is the simplest type 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 are aligned 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 layout has a vertical orientation new rows are placed one on top
property can be set to:
of the other.• A horizontal layout uses a side‐by side‐ column placement policy.
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. independent pixels )• margin ( dp – dev. independent pixels )
The LinearLayout ‐ Orientation<LinearLayout
1.1 Attribute: OrientationThe android:orientation
horizontalhorizontal for columns, or
vertical for rows.Use setOrientation() for runtime changes.
"wrap content"
vertical
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/myLinearLayout"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="horizontal"android:padding="4dp" >
<TextViewandroid: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" />
<EditTextandroid:id="@+id/ediName"android:layout_width="wrap_content"android:layout_height= wrap_contentandroid:text="Maria Macarena"android:textSize="18sp" />
<Buttonandroid:id="@+id/btnGo"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="Go"android:textStyle="bold" />
</LinearLayout> 20
The LinearLayout – Fill Model1.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 space allocation
(height, width) even if no text is initially provided (as is the case of the empty text box shown below).
natural sizesempty screen space
The LinearLayout – Fill Model1.2 Fill Model
All widgets inside a LinearLayout must include ‘width’ and ‘height’ attributes.
android:layout_widthandroid:layout_height
Values used in defining height and width can be:
1. A specific dimension such as 125dp (device independent pixels, a.k.a. dip )
2. wrap_content indicates the widget should just fill up its natural space.
3. match_parent (previously called ‘fill_parent’) indicates the widget wants to be as big as the enclosing parent.
The LinearLayout – Fill Model<?xml version="1.0" encoding="utf‐8"?><LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
1.2 Fill Model
125 dp
entire row (320 dp on medium resolution screens)
android:id="@+id/myLinearLayout"android:layout_width="match_parent "android:layout_height="match_parent "android:background="#ff0033cc"android:orientation="vertical"android:padding="4dp" >
<TextViewandroid:id="@+id/labelUserName"android:layout_width="_parent"android:layout_heigh
t="wrap_content "android:background="#ffff0066"android:text="User Name"android:textColor="#ff000000"android:textSize="16sp"android:textStyle="bold" />
<EditTextandroid:id="@+id/ediName"android:layout_width="match_parent
"android:layout_heigh
t="wrap_content "android:textSize="18sp" />
<Buttonandroid:id="@+id/btnGo"android:layout_width="125dp"android:layout_heigh
t="wrap_content "android:text="Go"android:textStyle="bold" />
Row‐wise
Use all the row
Specific size: 125dp
. </LinearLayout>
space
The LinearLayout – Weight1.2 WeightIndicates how much of the extra space in the LinearLayout will be allocated to the view. Use 0 if the view should not be stretched. The bigger the weight the larger the extra given to that widget.
ExampleThe XML specification for this window is similar to the previous example.
The TextView and Button controls 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 indicate how a 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 possible arrangements:left, center, right, top, bottom, etc.
Button has right
layout_gravity
at
The LinearLayout – Gravity
1.3 CAUTION: gravity vs. layout_gravity
The difference between:
android:gravityindicates how to place an object within a container. In the example the text is centered android:gravity="center"
android:layout_gravitypositions the view with respect to its
android:layout_gravity="center"
The LinearLayout – Padding
1.4 Padding
• The padding attribute specifies the widget’s internal margin (in dp units).
• The internal margin is the extra space between 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
<EditTextandroid:id="@+id/ediName"android:layout_width="match_parent"android:layout_height="wrap_content"android:textSize="18sp"android:padding="30dp" />
...
The LinearLayout – Margin
1.4 (External) Margin• Widgets –by default– are tightly packed next to each other. • To increase space between them use the android:layout_margin attribute
Increased inter widget‐ space
<EditTextandroid:id="@+id/ediName"android:layout_width="match_parent"android:layout_height="wrap_content"android:textSize="18sp"
android:layout_margin="6dp"></EditText>...
The Relative Layout
2. Relative Layout
The placement of widgets in a RelativeLayout is based on their positionalrelationship to other widgets in the container and the parent container.
AExample:A is by the parent’s topC is below A, to its rightB is below A, to the left o
B C
The Relative Layout
2. Example: Relative Layout
Location of the button is expressed in reference to its relative position with respect to the EditText box.
The Relative Layout
2. Referring to the containerBelow there is a list of some positioning XML boolean properties (=“true/false”) useful for collocating a widget based on the location of its parent container.
android:layout_alignParentTopandroid:layout_alignParentBottom
android:layout_alignParentLeftandroid:layout_alignParentRight
android:layout_centerInParentandroid:layout_centerVertical
android:layout_centerHorizontal
The Relative Layout
2. Referring to other widgets
The following properties manage the 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 (known as “@+id/wid1” )
wid2
wid1 wid2
The Relative Layout
2. Referring to other widgets – cont.
android:layout_alignTop=“@+id/wid1” wid1 wid2
android:layout_alignBottom =“@+id/wid1” an
dr
oid:layou
only to
t_alignLeft=“@+id/wid1”
android:layout_alignRight=“@+id/wid1”
wid1
wid1
wid2
wid2
wid1
wid2
The Relative Layout
2. Referring to other widgets
When using relative positioning you need to:
1. Use identifiers ( android:id attributes ) on all elements that you will be referring to.
2. XML elements are named using the prefix: @+id/... For instance an EditText box could be called: android:id="@+id/txtUserName"
3.You must refer l widgets that have been already defined. For instance a
new control to be positioned below the txtUserName EditText box could refer to it using: android:layout_below="@+id/txtUserName"
The Relative Layout2. Example<RelativeLayoutxmlns: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" >
<TextViewandroid: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> <EditTextandroid: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>
<Buttonandroid: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>
<Buttonandroid: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 the grid are identifiable by rows and columns.3. Columns are flexible, they could shrink or stretch to accommodate their
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 TableRow is determined by the total of side‐by‐
side widgets 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 TableLayout have three rows, one with two widgets, one with three widgets, and one with four widgets, there will be at least four columns.
0 10 1 2
0 1 2 3
Basic XML Layouts ‐ Containers
3. Table Layout – Stretching a Column
• A single widget in a TableLayout can occupy more than one column.
• The android:layout_span property indicates the number of columns the widget is allowed to expand.
<TableRow><TextView android:text="URL:" /><EditTextandroid:id="@+id/entry"android:layout_span="3" />
</TableRow>
Google Maps Android API V2
Tutorial – Hello GoogleMapBased on: https://developers.google.com/maps/documentation/android/start
• We'll create a simple Activity that shows asimple map.
• The map displays two markers: onerepresents a location in Cleveland Ohio, andthe other is on San Jose Costa Rica.
• The markers are connected by a straight line.
7
Tutorial – HelloGoogleMapBased 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 Workspaceand click Next.
• Select Browse..., enter <android-sdk-folder>/extras/google/google_play_services/libproject/google-play-services_lib, and click Finish.
Module IVSensors
Google Maps Android API V2
Tutorial – HelloGoogleMapBased on: https://developers.google.com/maps/documentation/android/start
Part 1.
One Time Operation – Prepare your Eclipse Workspace
• After completing previous steps yourworkspace should include a new projectcalled google-play-services_lib.
9
Google Maps Android API V2
Tutorial – HelloGoogleMapBased on: https://developers.google.com/maps/documentation/android/start
Part 2. Creating the App1. Create a new Android project, call it: HelloGoogleMap (minimum level API 11).2. To establish a dependency between your Project and 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 – HelloGoogleMapBased on: https://developers.google.com/maps/documentation/android/start
Part 2. Creating the App
3. Check that an updated Google_Play_Services lib is available on the device (you willneed a ‘real’ working device for testing, at this time the Emulator does not supportGMS 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 – HelloGoogleMapBased 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:
<fragmentxmlns: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 – HelloGoogleMapBased 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 isprogrammatically controlled through the GoogleMap map class levelvariable. Add the following statement to your onCreate method.
map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
6. Add the following lines into your AndroidManifest.xml (insert thembefore 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 – HelloGoogleMapBased on: https://developers.google.com/maps/documentation/android/start
Part 2. Creating the App
7. Modify the app’s AndroidManifest.xml file with the following permissions andfeatures requests
<uses-featureandroid: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 – HelloGoogleMapBased on:https://developers.google.com/maps/documentation/android/start
Part 2. Creating the App
8. Test your app. It should show a map of theworld centered on coordinates 00,00 (AtlanticOcean, west of Africa)
9. Attribution Requirements.“… you must include the Google Play Servicesattribution text as part of a "Legal Notices"section in your application.Including legal notices as an independentmenu item, or as part of an "About" menuitem, is recommended. The attribution text isavailable by making a call to “
GooglePlayServicesUtil.getOpenSourceSoftwareLicenseInfo(context);
Google Maps Android API V2
Tutorial – HelloGoogleMapBased on: https://developers.google.com/maps/documentation/android/start
Part 3. Improving the App – Adding a Marker
10. Modify your onCreate method. Add a call to the setUpMap method given below
private void setUpMap () {// test that we have a map already instantiatedif (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 mapsmap.setIndoorEnabled(false);
// this point represents location of Cleveland State UniversityLatLng 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 – HelloGoogleMapBased 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, rotatemapUI.setAllGesturesEnabled(true);// enable compassmapUI.setCompassEnabled(true);// enable zoom controlsmapUI.setZoomControlsEnabled(true);
}}
}// setUpMapIfNeeded
17
Google Maps Android API V2
Tutorial – HelloGoogleMapBased on: https://developers.google.com/maps/documentation/android/start
Part 4. Improving the App – Adding PolyLines
11. Modify the setUpMap method introduced in the previous section. Replace thestatement map.movecamera... with the following next lines
// this marker represents Universidad de Costa RicaLatLng 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 pointsPolyline line = map.addPolyline(new PolylineOptions()
.add( SANJOSE1_CR, CSU_OHIO )
.width(2)
.color(Color.BLUE));// this point is halfway between Cleveland and San JoseLatLng 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 –HelloGoogleMapBased on:https://developers.google.com/maps/documentation/android/start
Part 4. Improving the App – Adding PolyLines
12. Test your application.
Module VBluetooth, NFC, Networks, and Wi-Fi
Creating a Bluetooth client socket
private void connectToServerSocket(BluetoothDevice device, UUID uuid) {try{
BluetoothSocket cl ientSocket= device.createRfcommSocketToServiceRecord(uuid);
// Block until server connection accepted.clientSocket.connect();
// Start listening for messages.l istenForMessages(cl ientSocket);
// Add a reference to the socket used to send messages.transferSocket = clientSocket;
} catch (IOException e) {Log.e(“BLUETOOTH”, “Bluetooth client I/O Exception”, e);
}}
Sending and receiving strings using Bluetooth Sockets
private void listenForMessages(BluetoothSocket socket,Str ingBui lder incoming) {
listening = true;int bufferSize = 1024;byte[] buffer = new byte[bufferSize];try {
InputStream instream = socket.getInputStream();int bytesRead = -1;while (listening) {bytesRead = instream.read(buffer ) ;if (bytesRead != -1) {
String result = “”;while ((bytesRead == bufferSize) &&
(buffer[bufferSize-1] != 0)){result = result + new String(buffer, 0, bytesRead - 1);bytesRead = instream.read(buffer) ;
}result = result + new String(buffer, 0, bytesRead - 1);incoming.append(result);
}socket.close();
}} catch (IOException e) {
Log.e(TAG, “Message received failed.”, e);}finally {}
}
Listening for NFC tags
<activity android:name=”.BlogViewer”><intent-filter>
<action android:name=”android.nfc.action.NDEF_DISCOVERED”/><category android:name=”android.intent.category.DEFAULT”/><data android:scheme=”http”
android:host=”blog.radioactiveyak.com”/></intent-filter>
</activity>
Extracting NFC tag payloads
Str ing action = getIntent().getAction();if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)) {
Parcelable[] messages =intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
for (int i = 0; i < messages.length; i++) {NdefMessage message = (NdefMessage)messages[i];NdefRecord[] records = message.getRecords();
for (int j = 0; j < records. length; j++) {NdefRecord record = records[j];// TODO Process the individual records.
}}
}
Module VII/O file
+ "\n"
Android FilesExample 0: Reading a Resource File (see previous figure)
//reading an embedded RAW data filepublic class File1Resources extends Activity {
TextView txtMsg;@Overridepublic 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 FilesExample 1: Reading a Resource File (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 FilesExample 2: (Internal Storage ) Read/Write an Internal File.
In this example an application collectsdata from the UI and saves it to apersistent data file into the (limited) internalAndroid System space area.
Next time the application is executed theResource File will be read and its data shownon the UI
9
Android FilesExample 2: (Internal Storage ) Read/Write an Internal File.
The internal resource file is privateand cannot be seen by other appsresiding 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 " />
<EditTextandroid: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 FilesExample 2: Grab data from screen, save to file, retrieve from file 1/3.public class File2WriteRead extends Activity {
private final static String FILE_NAME = "notes.txt";private EditText txtMsg;@Overridepublic 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
Android FilesExample 2: Grab data from screen, save to file, retrieve from file 2/3.
public void onStart() {
"/data/data/cis470 filewriteread/files/"
super.onStart();try {
InputStream inputStream = openFileInput(FILE_NAME);if (inputStream != null) {
InputStreamReader inputStreamReader = newInputStreamReader(inputStream);
BufferedReader reader = new BufferedReader(inputStreamReader);String str = "READING FROM EXISTING DISK\n";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();}
}// onStart13
Android FilesExample 2: Grab data from screen, save to 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
Example 1. Create a SQLite Databasepackage cis70.matos.sqldatabases;public class SQLDemo1 extends Activity {
SQLiteDatabase db;@Overridepublic void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);setContentView(R.layout.main);// this provides the 'real' path name to theexternal SD cardString 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 DatabasesExample 1.Create a SQLite Databaseusing Internal Memory
Android’s System Image:
Module VIIDatabase
/data/data/cis470.matos.sqldatabases/myfriendsDB
8
SQL DatabasesExample2An alternative way of opening/creating a SQLITE database in your localAndroid’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 name of thenewly created database file will be:
/data/data/cis493.sql1/databases/myfriendsDB
This file could later be used by other activities in the app or exported out of theemulator (adb push…) and given to a tool such as SQLITE_ADMINISTRATOR (seenotes at the end).
SQL DatabasesExample2An alternative way of opening/creating a SQLITE database in your localAndroid’s System Image is given below
SQLiteDatabase db = this.openOrCreateDatabase("myfriendsDB2",
MODE_PRIVATE,null);
Where:1. “myFriendsDB2” is the abbreviated file path. The prefix is assigned by
Android as: /data/data/<app namespace>/databases/myFriendsDB2.
2. MODE could be: MODE_PRIVATE, MODE_WORLD_READABLE, andMODE_WORLD_WRITEABLE. Meaningful for apps consisting of multiplesactivities.
3. null refers to optional factory class parameter (skip for now)
Module VIIINetworking
Consuming Web Services
Example ‐ How .NET Web Services Are Called?Our example code consists of two fragments which implement the server and client side of the application.
Server Side:• The document http://support.microsoft.com/kb/301273 describes how to
create a simple Web service running on a Windows IIS‐Server.
Client Side:• We use the KSOAP 2.0 platform to request a sequence of remote procedure
calls to the IIS server hosting our service code. • The methods include functions taking zero, or more arguments.• Arguments send/received can be simple data 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 SolutionThere 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 ServicesExample – TUTORIAL – IIS Server Side Code
Services Available at the IIS Server
Consuming Web ServicesExample – TUTORIAL – IIS Server Side Code
Android App accessing all services available at the IIS server
Consuming Web ServicesExample – 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 are assembled2. EnglishDistance (Serialized Class) 3. WebServiceCall deals with HTTP
transporting of therequest/response and envelope objects
Consuming Web ServicesExample – TUTORIAL – Android Application
A fragment of the Android Main class follows
public class Main extends Activity {public TextView txtMsg;
@Overridepublic 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 resultint intResult = webServiceCall.AddService(11, 22);txtMsg.append( "\nAdd RESULT= " + intResult );
}
All the intelligent work is done by the WebServiceCall class.
Consuming Web ServicesExample – TUTORIAL – Android Application
The WebServiceCall class negotiates the transporting of request/response objects 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 ServicesExample – 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 ServicesExample 1 – TUTORIAL – Android Application
Fragment of the WebServiceCall class called to add two numbers. Here input parameters
and output values resulting from the webservice are sent and received. (cont. 3/4)public int AddService(int v1, int v2){
int intResult = 0;// indicate webservice (endpoint) to be calledfinal String webMethod = "Add";
// Create the outgoing request messagefinal 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 serverfinal SoapSerializationEnvelope envelope =
new SoapSerializationEnvelope(SoapEnvelope.VER11);envelope.dotNet = true;
// place in envelope the outgoing request objectenvelope.setOutputSoapObject(requestObject);
Consuming Web ServicesExample 1 – TUTORIAL – Android Application
The WebServiceCall class (continuation 4/4)
try{
Web service is
called here
// call webmethod and parse returning response objectfinal 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 IXDeveloping Android Services
1. Using Eclipse, create a new Android project and name it Services2. Add
a new Java Class file to the project and name it MyService. Populate the MyService.java file with the following code:
package net . learn2develop.Services;
import android.app.Service;import android.content.Intent;import android.os.IBinder;import android.widget.Toast;
public class MyService extends Service {
@Overridepublic IBinder onBind(Intent arg0) {
return null;}
@Overridepublic int onStartCommand(Intent intent, int flags, int startId) {
// We want this service to continue running unti l it is explicitly// stopped, so return sticky.Toast.makeText(this, “Service Started”, Toast.LENGTH_LONG).show();return START_STICKY;
}
@Overridepublic void onDestroy() {
super.onDestroy();Toast.makeText(this, “Service Destroyed”, Toast.LENGTH_LONG).show();
}}
3. In the AndroidManifest.xml file, add the following statement in bold:<?xml version=”1.0” encoding=”utf-8”?><manifest xmlns:android=”http://schemas.android.com/apk/res/android”
package=”net. learn2develop.Services”android:versionCode=”1”android:versionName=”1.0” >
<uses-sdk android:minSdkVersion=”14” />
<applicationandroid:icon=”@drawable/ic_launcher”android:label=”@string/app_name” >
<activityandroid:label=”@string/app_name”android:name=”.ServicesActivity” ><intent-filter >
<action android:name=”android. intent.action.MAIN” />
<category android:name=”android.intent.category.LAUNCHER” /></intent-filter>
</act ivity><service android:name=”.MyService” />
</application>
</manifest>
4. In the main.xml file, add the following statements in bold, replacing TextView:<?xml version=”1.0” encoding=”utf-8”?><LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android”
android:layout_width=”fill_parent”android:layout_height=”fill_parent”android:orientation=”vertical” >
<Button android:id=”@+id/btnStartService”android:layout_width=”fill_parent”android:layout_height=”wrap_content”android:text=”Start Service”android:onClick=”startService”/>
<Button android:id=”@+id/btnStopService”android:layout_width=”fill_parent”android:layout_height=”wrap_content”android:text=”Stop Service”android:onClick=”stopService” />
</LinearLayout>
5. Add the following statements in bold to the ServicesActivity.java file:package net . learn2develop.Services;
import android.app.Activity;import android.content.Intent;import android.os.Bundle;import android.view.View;
public class ServicesActivity extends Activity {/** Called when the activity is first created. */@Overridepublic void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);setContentView(R.layout.main);
}
public void startService(View view) {startService(new Intent(getBaseContext(), MyService.class));}
public void stopService(View view) {stopService(new Intent(getBaseContext(),
MyService.class));}
}
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 XAudio and Video
MediaPlayer – Playing Audio from a Raw Resource<?xml version="1.0" encoding="utf-8"?><LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"android:orientation="vertical"android:layout_width="fill_parent"android:layout_height="fill_parent"><TextViewandroid: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="STOP Music"/></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(),"Bravo! 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}