You are on page 1of 131

Android

Programming
A Step By Step Guide for Beginners!
Create Your Own Apps!

Kevin Lyn.

Copyright 2015 by Kevin Lyn.

All rights reserved. No part of this publication may be reproduced, distributed, or
transmitted in any form or by any means, including photocopying, recording, or other
electronic or mechanical methods, without the prior written permission of the author,
except in the case of brief quotations embodied in critical reviews and certain other
noncommercial uses permitted by copyright law.
Disclaimer
While all attempts have been made to verify the information provided in this book, the
author doesnt assume any responsibility for errors, omissions, or contrary interpretations
of the subject matter contained within. The information provided in this book is for
educational and entertainment purposes only. The reader is responsible for his or her
own actions and the author does not accept any responsibilities for any liabilities or
damages, real or perceived, resulting from the use of this information.

Table of Contents

Book Description
Introduction
Chapter 1: Definition
Chapter 2: Basics of Android Programming
How to create a Project
Running the Application
Running the App on the Emulator
Chapter 3: Structure of an Android Application
Chapter 4: User Interface in Android
Types of Android Layouts
Attributes of Android Layout
User Interface controls in Android
How to create User Interface Controls
Chapter 5: Event Handling in Android
Using an Anonymous Inner Class to Register an Event Listener
Using an Activity implements Listener Interface to Register an Event Listener
Chapter 6: Advanced features in Android
Toasts
Normal toasts
Location Based services in Android
Getting the Location Address in Android
Installation of Google Play services
Creating the app
Sending Email in Android

Sending SMS in Android


Making Phone Calls
Android camera
Conclusion

Book Description


This book is about android programming. Its emphasis is to guide programmers and
especially beginners, on how to develop amazing android apps. The book starts by
explaining what an android is and its origin. The next thing is how to get started, including
setting up the environment ready for programming, creating a new android project, and as
well as how to run an android app, whether on the emulator or on the physical device.

The components of an android project are also explained. Many features which can be
included in an amazing android app, have been explored with code examples, on how to
implement them. By reading this book you will learn what toasts are and how to develop
them.

You will also learn how to implement notifications in android. Apps can also support
Bluetooth and the use of cameras. You will learn how to develop apps with these features.
The main purpose of most of these devices is to facilitate communication between parties.

This book will teach you to understand how to develop apps which supports calling,
sending SMS and email. These are all explained chronologically and in a simple manner
for better understanding. For further explanation pictures have also been used.s

The following topics are explored in detail:


Definition
Basics of Android Programming
Structure of an Android Application
User Interface in Android
Event Handling in Android
Advanced Features in Android:
Toasts
Notifications
Location Based Services
Sending Email
Sending SMS
Making Phone Calls
Android Camera
Android Bluetooth





Introduction


The use of devices running android operating system has increased and it is still showing
potential for future growth. These devices range from mobile phones to tablets. This
explains the need for numerous android apps, to satisfy the different requirements of the
users of these devices.

Most people using these apps view them as complex to develop. However this is not the
case. With android programming one can create amazing apps for his own devices. One
can also upload the apps on Google Play, from where other device users can download
them.

Android apps also pay well, since they are purchased at a high price. The demand for
android developers is on the rise, and you as programmer or potential programmer should
take advantage of this fact.




Chapter 1:

Definition

Android is an operating system which runs on mobile phones and tablets.The
operating system is designed to be run on mobile devices with a touch
screen. Android programming is the kind of programming, whereby applications are
developed to be run on the Android operating system.

Expert java developers find it easier to learn Android programming, since the complex
part of this programming is based on java. What happens in android programming is that,
the programmer creates the user interface using XML coding. To add functionality, which
most programmers try to find tougher, they have to use java.

This clearly explains why, expert java developers will always find it easy to program in
android. It is not a must for you to use XML to create the user interface, but java can also
be used for this purpose. The problem is that too much coding is needed, when the
interface is created using java.

In XML, one can also drag and drop components, as opposed to coding from scratch. This
way is very simple, especially for beginners. The programmer can also adjust how these
components are aligned on the screen, so as to achieve the intended alignment.

By July 2003, over 1 million android Apps had been created. They had also recorded more
than 25 million downloads. This clearly shows how device users have great need for
android Apps. Worldwide,the majority of mobile phones in use run android operating

systems. This shows how wide the market for android apps is and it is still growing.

Getting started

Before you can start programming in android, you need to set up the necessary tools first.
The following are the prerequisites:

1. Java Development Tool kit (JDK)/ Java Runtime Environment (JRE) These must
be installed, before you install the IDE. If
you try to install any of the IDEs before installing one of these, the installation will
fail , so make sure that you download and install them beforehand. JDK and
JRE serve the same purpose when it comes to android programming, so you can
choose to download and install any of them. They are available for free download.

2. Development tool

Currently, Google provides two common android development tools. These are the
Android Studio and Android Development Tools (ADT). Android studio is based
on IntelliJ whereas the ADT is based on Eclipse.

If you are a java developer you might have come across the Eclipse. Unlike the
ADT, Android studio supports the Gradle build system, which is a new technology
in Android. If you want to enjoy this feature then install the Android studio.


If you find it easier to work with eclipse, you can download the ADT bundle. This
comes with both Eclipse and SDK tools installed, so after extracting it, you can get
started. You can also download the eclipse on its own and then download the SDK
tools. These can then be integrated. If you experience any difficulty while
integrating the two, just look up online for manuals on how to do it.




Chapter 2:
Basics of Android Programming


Before creating your first app in android, you should learn how to create a project and how
to use it. Note, that in android any new app that you create comes with a simple Hello
World. This comes by default since is built in.

How to create a Project



For you to be able to create a project in Android, just follow the steps below:
1. Click on File and select New
2. Choose Project followed by Android Project.


Note that after this, doing it the next time it will be easier, as shown below:

File->New->Android Project


There are options which need to be filled in. These are explained below:

Project Name- this is the name of the project. Its first letter must be in
Upper case.
Build Target- this is the version of android that you need to use. You can
choose 2.2, since most devices worldwide use this.
Application name- this is the title to be shown on the title bar of the
android, once the app is run on an android device.
Package name- name it as com.company.project. Note ,that every app on
your device belongs to a different and unique package.
Create activity- javas top-level class name.
Min SDK version- this should match the build target.

Running the Application



After creating the project, you may notice that it came with the default Hello world, as
an example. In this section you will learn how to run it and observe the output.

You can run the application on your real device, such as a mobile phone or you can use the
emulator which is inbuilt with the development environment. For those using windows
and wanting to run the application on the physical device, you must install the necessary
drivers beforehand.

After installing the drivers, you then need to set up the device to be ready for accepting the
application to be run on it. This is done by turning on USB debugging on the device,
which is a feature made available for use by the developers. If your device is running the
earlier versions of android, you can find it in:

Settings->Applications->Development

If your device is running android 4.0 and above, find it in:

Settings->Developer options

Devices running android version 4.2 and newer, will have the Developer options hidden

by default . This can be enabled by navigating to:



Settings-> About phone.

Then you can tap seven times on Build number and you will find the Developer options
on the previous screen. Now that you are through with the settings you can run your App.
Just click on Run and select the device on the dialog that will appear. Look at the output
on your physical device.

Running the App on the Emulator



Whether you are using the ADT or Android studio, you can run your application on the
Emulator. You only need to set up the AVD (Android Virtual Device) and it will be done.
To set up the AVD on Eclipse navigate as follows:

Window > Android Virtual Device Manager

In Android studio navigate as follows:

Tools > Android > AVD Manager


Note that it is better to start the AVD before running the application, since you can set it to
be the way you want it to be in terms of size and appearance. To run the application on the
emulator just select the project and click on Run. Select to run on the emulator and
watch the output.

Chapter 3:
Structure of an Android Application


The android application has many components, all of which can be found in the project.
These are explained below:

1. src- by default, it contains a class named MainActivity.java. The .java source files for
your project will be contained in this class.
2. gen- the .R file is contained here, and is responsible for the reference of your projects
resources.
3. bin- the package files .apk are contained here, and everything else needed to run the
project.
4. res/drawable-hdpi- contains the drawable objects of the project.
5. res/layout- this folder contains the .XML file that defines the layout of your application.
6. res/values- has numerous resources,such as, definitions for colors and strings.
7. AndroidManifest.xml- defines the characteristics of your app. It also defines each
element contained in the app.

Chapter 4:
User Interface in Android


The user interface of android can have a number of components, including buttons, text
fields and others. The GUI of android is defined in the XML file. Consider the code shown
below:

<?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 >
<TextView android:id=@+id/tv
android:layout_width=wrap_content
android:layout_height=wrap_content
android:text=a text view />
<Button android:id=@+id/btn
android:layout_width=wrap_content
android:layout_height=wrap_content

android:text= a button />



<!You can add more GUI elements here >

</LinearLayout>


You can see an example of the XML file above. Note that we have created two elements, a
text view and a button. We have given them an id, which will be used to identify them. We
have also sized them in the intended way, whereby using the wrap_content in the two
cases.
It means that none will span the whole of the devices screen. The text to appear on each
element has also been specified. We have used Linear Layout. We can then load the layout
resource. This can be done on the application code as shown below:

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}

Types of Android Layouts



The purpose of different layouts in android is to create a different look, feel and view of
the created android apps.

1. Linear Layout- all the children are arranged in a single direction, either
horizontally or vertically.
2. Table Layout- views are grouped into rows and columns.
3. Relative Layout- child views are displayed in relative positions.
4. Frame Layout- can be used to display a single view on the screen, since it
acts as a placeholder.
5. Absolute Layout- with this layout, you are able to specify exactly where the
children will be located.
6. Grid view- items are displayed in a scrollable two-dimensional grid.
7. List View- used to display items which can scroll.

Attributes of Android Layout



1. android:layout_height- defines the layouts height.
2. android:layout_width- defines the layouts width.
3. android:id- this is the identifier of the component.
4. android:layout_marginTop- the space above the layout.
5. android:layout_marginBottom- space at the bottom of the layout.
6. android:layout_marginRight- space to the right of the layout.
7. android:layout_marginLeft- the space to the left of the layout.
8. android:layout_gravity-defines how the child views will be positioned.
9. android:layout_weight- defines the allocation of views to the extra space in
the layout.

Note that if you set either the width or height of the view to wrap_content, it will only
size itself to fit its content. If you set it to fill_parent, it will size itself so as to be of the
same size as the parent view. Gravity is important in positioning the view on the screen.
You should note that the syntax for creating the identity of any view is:

android:id= @+id/btn

To instantiate an object of the button in the java class from the layout, do as
follows:

Button button= (Button) findViewById (R.id.btn)
This also applies to the other elements of the layout.

User Interface controls in Android



The user interface in android can be made of a number of elements. You can use any of
them depending on what you want to achieve. These controls include the following:

1. TextView- displays text to users.
2. EditText- displays the text but the user is able to edit it.
3. Button- a push-button. The user can click or press to get an action.
4. AutoCompleteTextView- displays editable text just like EditText, but it
suggests some texts to you while you are typing.
5. ImageButton- you can use this to display an image.
6. ToggleButton- it has a light indicator which can be turned on or off.
7. CheckBox- represents choices which are not mutually(??) exclusive.
8. ProgressBar- this shows the progress of a task, especially the one running on
the background.
9. RadioButton- this can be in a checked or unchecked state.
10. Spinner- allows users to select their choice from a drop-down list.
11. DatePicker- makes it possible for users to select a date.

12. TimePicker- users are able to select time in either AM/PM or 24 hour format.

How to create User Interface Controls


Creation of any user interface control involves specifying its ID, size, position and also if
possible the text to be displayed on the control. Consider the code shown below:

<?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 >

<TextView android:id=@+id/tv
android:layout_width=wrap_content
android:layout_height=wrap_content
android:text=This is a TextView />
</LinearLayout>

We have created a Text view and given it the id tv. This will be solely used to identify it.
Within the code we have created , we have also specified its width and height to
wrap_content, meaning that it will stretch only to fit its contents. In our java class we
need to instantiate this TextView. This will be achieved as follows:

TextView view= (TextView) findViewById (R.id.tv)



We have now created the object view, which is an example of the TextView tv.
Having created a TextView and a Button, and being learned how to instantiate them, you
must have by now realized that the process is very simple. The same procedure applies to
create other controls.

Chapter 5:
Event Handling in Android


The user interface alone in android is not enough. There is a need to add functionality or
events to it. An example is a button. We need to specify what the button should do, once it
has been clicked or pressed. With android events, the following concepts are very
important:

1. Event Listeners- this is the object responsible for receiving notifications
whenever an event happens.
2. Event Listeners Registration- event registration occurs when the event
handler and the event listener are registered. Whenever the event listener fires an
event, the handler will be called.
3. Event Handlers- this method is responsible for the real handling of the event.
For it to work, it must be registered with the event listener.

Using an Anonymous Inner Class to Register an Event


Listener

Open your IDE and create a project. Modify the activity_main.xml to be as follows:
<?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/btn1
android:layout_height=wrap_content
android:layout_width=match_parent
android:text=Small Font/>
<Button
android:id=@+id/btn2
android:layout_height=wrap_content
android:layout_width=match_parent
android:text=Large Font/>
<TextView

android:id=@+id/tv
android:layout_width=wrap_content
android:layout_height=wrap_content
android:capitalize=characters
android:text=Hello world! />
</LinearLayout>

The class MainActivity.java should be as follows:
import android.os.Bundle;
import android.view.View;
import android.app.Activity;
import android.view.Menu;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

// instantiate the buttons

Button b1 = (Button) findViewById(R.id.btn1);


Button b2 = (Button) findViewById(R.id.btn2);

// register the first button to the click event
b1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// instantiate the text view
TextView txtv = (TextView) findViewById(R.id.tv);
// alter size of text
txtv.setTextSize(14);
}
});

// register the second button and the click event
B2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// instantiate the text view
TextView txtv = (TextView) findViewById(R.id.tv);
// alter size of text
txtv.setTextSize(24);
}

});
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}

The above are the two classes which you need to modify. The other classes will be in their
correct state by default. After you have prepared your AVD you can now run your project.
If you are using the physical device, you will be alright. Just open one of the classes of the
project and click on Run. The following will be displayed:


The first two are the buttons with the text we have set in the activity_Main.xml file. The

last part shows the Text View, with the text which we have also specified in the
Activity_Main.xml file. Note that the text on the Text View is not editable. For the
buttons size we set the height to wrap_content.

This explains why the heights have only stretched to accommodate the text displayed on
the buttons. In the case of the width we set it to match_parent, and thus, they are
stretching up to the ends of the screen of the emulator. Try to click any of the buttons, and
you will notice that the size of the text displayed on the text view, will change to size 14.
This applies to both buttons.

Using an Activity implement Listener Interface to Register


an Event Listener

In this method the set OnClickListener is used. It is most suitable when your application
has only a single control. If the application has numerous ones, additional programming is
needed for you to determine the control which triggered an event. This is also easy, as it
can be achieved by using the case statement. Using our previous project, just modify the
MainActivity.java, to be as follows:

import android.os.Bundle;
import android.view.Menu;
import android.app.Activity;
import android.view.View.OnClickListener;
import android.view.View;
import android.widget.TextView;
import android.widget.Button;

public class MainActivity extends Activity implements OnClickListener {

@Override
protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

// instantiate the two buttons
Button b1 = (Button) findViewById(R.id.btn1);
Button b2 = (Button) findViewById(R.id.btn2);


// register first button and the click event
b1.setOnClickListener(this);
// register second button and the click event
b2.setOnClickListener(this);
}

// Implementing the OnClickListener method
public void onClick(View v) {
if(v.getId() == R.id.btn1)
{
// instantiate the Text view
TextView txtv = (TextView) findViewById(R.id.tv);
// alter the size of text

txtv.setTextSize(14);
return;
}
if(v.getId() == R.id.btn2)
{
// instantiate the text view
TextView txtv = (TextView) findViewById(R.id.tv);
// alter the size of the text
txtv.setTextSize(24);
return;
}
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

}

You have now learned how to register an Event Listener. The two methods give the same
result, so you can choose to use the one which you find yourself most familiar with.
Instead of using the previous two methods, you can choose to make work easier for
yourself, achieving this from the layout file, that is, the Activity_Main.XML. The
MainActivity.java class will look as follows:

import android.os.Bundle;
import android.view.Menu;
import android.app.Activity;
import android.widget.Button;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends Activity{

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}

// set the action for the first button.

public void setSmall(View v) {


// instantiate the text view
TextView txtv = (TextView) findViewById(R.id.tv);
// alter the size of the text
txtv.setTextSize(14);
return;
}
// implement the event for the second button.
public void setLarge(View v) {
// instantiate the text view.
TextView txtv = (TextView) findViewById(R.id.tv);
// alter the size of the text
txtv.setTextSize(20);
return;
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}


}

The Activity_Main.xml file for this class should be modified to the following:
<?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/btn1
android:layout_height=wrap_content
android:layout_width=match_parent
android:text=Small Font
android:onClick=setSmall/>
<Button
android:id=@+id/btn2
android:layout_height=wrap_content
android:layout_width=match_parent
android:text=Large Font
android:onClick=setLarge/>

<TextView
android:id=@+id/tv
android:layout_width=wrap_content
android:layout_height=wrap_content
android:capitalize=characters
android:text=Hello world! />
</LinearLayout>

In this case, we have specified the handler method via the android:setOnClick attribute in
the layout file.

Chapter 6:
Advanced features in Android

Toasts

These are a kind of view which are used to display little information to the user. The
message is displayed for a short period of time, after which the toast disappears. A good
example is when adjusting the volume. The toast is aimed at being , as much obstructive
as possible, so as to insist in the reading a particular message. There are two types of
toasts:

Normal toasts.

Custom toasts.

Normal toasts

Create a new project and call it ToastApp. Modify the xml file of the project to get the
following:

<?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/btn
android:text=Show Toast
android:layout_width=wrap_content
android:layout_height=wrap_content/>
</LinearLayout>

Modify the MainaActivity.java class to the following:

import android.app.Activity;
import android.view.View;

import android.os.Bundle;
import android.widget.Button;
import android.view.View.OnClickListener;
import android.widget.Toast;
public class MainActivity extends Activity {

private Button b;

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);
setContentView(R.layout.main);

b = (Button) findViewById(R.id.btn);

b.setOnClickListener(new OnClickListener() {


@Override
public void onClick(View v) {

Toast.makeText(getApplicationContext(),
Button is clicked, Toast.LENGTH_LONG).show();

}
});
}
}

Once you are finished, just select your project and click run. A button will appear written
Show Toast. Click on this button and you will get the result shown below:


Upon clicking the button, a text written Button is clicked will be shown. It will appear
on the screen for a few seconds and then disappear. This is an example of a normal toast.


Custom toast view:

This is just an advanced normal toast after it has been customized, maybe by adding some
images or other features to it. Using the project above, modify the xml file to the
following:

<?xml version=1.0 encoding=utf-8?>
<LinearLayout xmlns:android=http://schemas.android.com/apk/res/android
android:id=@+id/advanced_toast
android:layout_width=fill_parent
android:layout_height=fill_parent
android:orientation=horizontal
android:background=#FFF
android:padding=5dp >
<Button
android:id=@+id/btn
android:text=Show Toast
android:layout_width=wrap_content
android:layout_height=wrap_content/>
<ImageView
android:layout_width=wrap_content

android:layout_height=fill_parent
android:id=@+id/imgv
android:layout_marginRight=5dp />
<TextView
android:layout_width=wrap_content
android:layout_height=fill_parent
android:id=@+id/tv
android:textColor=#000 />
</LinearLayout>

Modify the MainActivity.java class to the following:

import android.app.Activity;
import android.view.Gravity;
import android.os.Bundle;
import android.view.View;
import android.view.LayoutInflater;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Button;

import android.widget.Toast;
import android.widget.TextView;

public class MainActivity extends Activity {

private Button b;

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);
setContentView(R.layout.main);

b = (Button) findViewById(R.id.btn);

b.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
LayoutInflater in = getLayoutInflater();

View ly = in.inflate(R.layout.custom_toast,

(ViewGroup) findViewById(R.id.advanced_toast));

ImageView iv = (ImageView) layout.findViewById(R.id.imgv);
iv.setImageResource(R.drawable.ic_launcher);

TextView t = (TextView) layout.findViewById(R.id.tv);
t.setText(Button is clicked!);

Toast tst = new Toast(getApplicationContext());
tst.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
tst.setDuration(Toast.LENGTH_LONG);
tst.setView(ly);
tst.show();
}
});
}
}

The custom toast might be somehow complex, but it is a very nice one. Take note of the
steps we have followed right up to the end. We have set a dummy image view. The toast
will also be displayed for longer, since we have set the duration to long. Upon running
the app and clicking the button, the following output will be seen:


That is all about toasts.



Notifications

The Notifications class is responsible for representing notifications in android. The
NotificationManager class and getSystemService() method, are also responsible for the
creation of notifications. These three are combined as follows:

NotificationManager nfnManager = (NotificationManager)
getSystemService(NOTIFICATION_SERVICE);

To create the Notification object, the Notification.Builder class is used. To specify the
action to be performed, once the user selects the notification, we use PendingIntent.
Create an xml file with the following coding:

<?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:orientation=vertical >
<Button
android:id=@+id/btn
android:text=Create Notification >
android:layout_width=match_parent
android:layout_height=match_parent
android:onClick=makeNotification
</Button>

Create another xml file called layout2.xml and add the following code to it:

<?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 >
<TextView
android:id=@+id/tv1
android:layout_width=wrap_content
android:layout_height=wrap_content
android:text=Activity opened from the notification >
</TextView>
</LinearLayout>
</LinearLayout>

Create another activity called ReceiveActivity and register it with AndroidManfest.mf file.
Add the following code to the activity:

import android.app.Activity;
import android.os.Bundle;
public class ReceiveActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout2);

}
}

Note that in the activity above, we are referring to the layout2 xml file rather than the
main xml file. Modify the activity class to the following:

import android.app.Activity;
import android.app.NotificationManager;
import android.app.Notification;
import android.app.PendingIntent;
import android.content.Intent;
import android.view.View;
import android.os.Bundle;
public class NotificationActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}

public void createNotification(View v) {

Intent in= new Intent(this, ReceiveActivity.class);


PendingIntent pIn = PendingIntent.getActivity(this, 0, in, 0);
Notification nt = new Notification.Builder(this)
setContentTitle(You have an mail from + example@gmail.com)
setContentText(Subject).setSmallIcon(R.drawable.icon)
setContentIntent(pIn)
addAction(R.drawable.icon, Call, pIn)
addAction(R.drawable.icon, More, pIn)
addAction(R.drawable.icon, And more, pIn).build();
NotificationManager nfnManager = (NotificationManager)
getSystemService(NOTIFICATION_SERVICE);
nt.flags |= Notification.FLAG_AUTO_CANCEL;
nfnManager.notify(0, nt);
}
}

Now that you have finished, just select the project and click Run. Watch the output. A
notification will be seen, telling you that you have an email from whom you have
specified in the code.

Location Based services in Android



Google play services make it possible for you to use android apps to get your location.
This location can be in terms of the Longitude, Latitude, timestamp, velocity, altitude and
bearing. There are some methods that can be applied to the location object, to get
information about location. Examples of these methods include the following:

1. float distanceTo(Location dest)- gives the distance between the current
location and another location.
2. double getAltitude()- gives the height above sea level in meters, if available.
3. float getBearing()- gives the bearing in degrees.
4. double getLAtitude()- gives the latitude in degrees.
5. Double getLongitude()- gives the longitude in degrees.

These are just a few of the available methods, so you can explore the rest and learn how to
use them in coding.

Getting the Location Address in Android



The Geocoder.getFromLocation() can be used to give both, the Latitude and the
Longitude, once we have got the Location object. This method takes a long time before it
displays the results, so it is advisable to run it in the background using the method
doInBackground(). This is because of the synchronous nature of the process.

Installation of Google Play services



Before developing an app to enable you getting into location address, Google play
services SDK need to be installed. This can be accomplished by the following simple
steps:

1. Start the SDK manager. If you are using Eclipse, click on Window->Android
SDK Manager.
2. Once launched, click on Extra. From the package list shown, search for
Google Play Services. If you dont find it, then it has not been installed. Install it.
3. On Eclipse, import it into the workspace by clicking on File > Import.
Finally, select Android > Existing Android Code into Workspace. Browse to
<android-sdk>/extras/google/google_play_services/libproject/. You will be finished
after importation. If you are using Android studio, copy :
<android-sdk>/extras/google/google_play_services/libproject/google-playservices_lib/ which is the library project to the location of your android projects.

Creating the app



Now that you have followed all the steps above, its time to create the app. Create a new
project and give it a name. The next step is to add the Google play service to the project.
To do this, just select the project and right click on it. Choose Build Path > Configure
Build Path > Android > Add. Double click on the Google_play_service_lib which will be
shown.


Modify the class activity_main.xml to the following:

<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/loc
android:layout_width=fill_parent
android:layout_height=wrap_content
android:text=Get Location/>
<Button android:id=@+id/dscon
android:layout_width=fill_parent
android:layout_height=wrap_content
android:text=Disconnect Service/>
<Button android:id=@+id/cnt
android:layout_width=fill_parent
android:layout_height=wrap_content
android:text=Connect Service/>
<TextView
android:id=@+id/locationLabel
android:layout_width=wrap_content
android:layout_height=wrap_content/>
<TextView
android:id=@+id/labaddress
android:layout_width=wrap_content
android:layout_height=wrap_content/>

</LinearLayout>

Modify the class MainActivity.java to the following:

import java.util.List;
import java.io.IOException;
import java.util.Locale;
import com.google.android.gms.common.GooglePlayServicesClient;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.location.LocationClient;
import android.location.Address;
import android.content.Context;
import android.os.AsyncTask;
import android.location.Geocoder;
import android.os.Bundle;
import android.location.Location;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.widget.Button;
import android.view.View;
import android.widget.Toast;

import android.widget.TextView;

public class MainActivity extends FragmentActivity implements
GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener
{
LocationClient mloc;
private TextView labeladdress;
private TextView labelloc;
private Button locbtn;
private Button disbtn;
private Button conBtn;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

labelloc = (TextView) findViewById(R.id.locationlabel);
labeladdress = (TextView) findViewById(R.id.labaddress);
locbtn = (Button) findViewById(R.id.loc);


locbtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
displayCurrentLocation();
}
});
disbtn = (Button) findViewById(R.id.dscon);
disbtn.setOnClickListener(new V.OnClickListener() {
public void onClick(View v) {
mLoc.disconnect();
labelloc.setText(you are disconnected.);
}
});
conbtn = (Button) findViewById(R.id.cnt);
conbtn.setOnClickListener(new V.OnClickListener() {
public void onClick(View v) {
mLoc.connect();
labelloc.setText(you are connected.);
}
});
mLoc = new LocationClient(this, this, this);

}
@Override
protected void onStart() {
super.onStart();
// Connection to the client.
Loc.connect();
labelloc.setText(you are connected.);
}
@Override
protected void onStop() {
// Disconnection from the client.
mLoc.disconnect();
super.onStop();
labelloc.setText(you are disconnected.);
}
@Override
public void onConnected(Bundle datamb) {
// Display the connection status
Toast.makeText(this, Connected, Toast.LENGTH_SHORT).show();
}
@Override

public void onDisconnected() {


// show the status of connection
Toast.makeText(this, Try to reconnect, you are disconnected.,
Toast.LENGTH_SHORT).show();
}
@Override
public void onConnectionFailed(ConnectionResult conResult) {
// show the error code if failure occurs
Toast.makeText(this, Failure in connection : +
conResult.getErrorCode(),
Toast.LENGTH_SHORT).show();
}
public void displayCurrentLocation() {
// Get the longitude and latitude of the current location
Location currLoc = mLoc.getLastLocation();
String message = Current Location: +
Double.toString(currLoc.getLatitude()) + , +
Double.toString(currLoc.getLongitude());

// current location will be shown on the screen
labelloc.setText(message);

// To show current address on the devices screen


(new GetAddressTask(this)).execute(currLoc);
}
/*

This will give the address as per the current latitude and longitude. It is a subclass of
AsyncTask
*/
private class GetAddressTask extends AsyncTask<Location, Void, String>{
Context mc;
public GetAddressTask(Context c) {
super();
mc = c;
}

/*
* the onPostExposure will display the address when the task is *finished.
*/
@Override
protected void onPostExecute(String a) {
// show the current address on the screen

labaddress.setText(a);
}
@Override
protected String doInBackground(Location params) {
Geocoder gcoder =
new Geocoder(mc, Locale.getDefault());
// getting the current location from the inputted parameter list
Location lc = params[0];
// Creating a list for containing the addresses
List<Address> ads = null;
try {
ads = gcoder.getFromLocation(lc.getLatitude(),
lc.getLongitude(), 1);
} catch (IOException e1) {
Log.e(LocationSampleActivity,
IO Exception in getFromLocation());
e1.printStackTrace();
return (IO Exception occurred in getting the address);
} catch (IllegalArgumentException e2) {
// Error message to be posted in the log
String errorMessage = Wrong arguments +

Double.toString(lc.getLatitude()) +
, +
Double.toString(lc.getLongitude()) +
already passed to address service;
Log.e(LocationSampleActivity, errorMessage);
e2.printStackTrace();
return errorString;
}
// If the a address is returned by the reverse geocode
if (ads != null && ads.size() > 0) {
// Obtain the first address
Address a = ads.get(0);
/*
* Formatting the first line of the address if available
*/
String aText = String.format(
%s, %s, %s,
// adding a street address if it is available.
a.getMaxAddressLineIndex() > 0 ?
a.getAddressLine(0) : ,
// A city is usually the locality

a.getLocality(),
// getting the addresses country
a.getCountryName());
// returning the value of text
return aText;
} else {
return Didnt find any address;
}
}
}// AsyncTask class
}

The string.xml file should be modified to the following:

<?xml version=1.0 encoding=utf-8?>
<resources>
<string name=app_name>LocationBasedServicesDemo</string>
<string name=action_settings>Settings</string>
<string name=hello_world>Hello world!</string>
<string name=loc>Get Location</string>
<string name=dscon>Disconnect Service</string>

<string name=cnt>Connect Service</string>


</resources>


The AndroidManifest.xml file should be modified to the following:
<?xml version=1.0 encoding=utf-8?>
<manifest xmlns:android=http://schemas.android.com/apk/res/android
package=com.example. LocationBasedServicesDemo
android:versionCode=1
android:versionName=1.0 >
<uses-sdk
android:minSdkVersion=8
android:targetSdkVersion=17 />
<uses-permission
android:name=android.permission.ACCESS_COARSE_LOCATION/>
<application
android:allowBackup=true
android:icon=@drawable/ic_launcher
android:label=@string/app_name
android:theme=@style/AppTheme >
<activity

android:name=com.example. LocationBasedServicesDemo.MainActivity
android:label=@string/app_name >
<intent-filter>
<action android:name=android.intent.action.MAIN />
<category android:name=android.intent.category.LAUNCHER />
</intent-filter>
</activity>
</application>
</manifest>


That is what it entails to work with location based services in android. The most important
thing is to install the Google play service SDK and the rest will be easy. It is better to use a
real device when running the above app, since the emulator may lack the necessary
features. Your SDK should also be updated to the latest version, otherwise you will get

errors.

Sending Email in Android



Sometimes, you might need to send an email from your android app. Using your device to
gmail, yahoo, outlook or other email accounts. Since these are available, you dont need to
create an email client. You only need to make this service available on your app. Intents
are used for this purpose. ATION_SEND is used to launch the already installed email
client on your device. The maito: will then be used to send the mail. You can add the
TO, SUBJECT, CC and TEXT to your email before sending. Other extra fields which can
be added include:

1. EXTRA_BCC- this string holds email address that it expected to be blind
carbon copied.
2. EXTRA_EMAIL- this string holds the email addresses to which the message
should be delivered to.
3. EXTRA_CC- holds emails that are expected to be carbon copied.
4. EXTRA_SUBJECT- a string which holds the subject line of the message.
5. EXTRA_HTML_TEXT- supplies the alternative to EXTRA_TEXT in
HTML format.
6. EXTRA_TEXT- supplies the data to be sent.

From the example below, you will learn how to use the Intent object for the purpose of
launching the email client installed on your device. The email will be sent to given clients.
Run the app on a physical device rather than on the emulator, since it might lack the
required features. The device should have the latest OS version. An email client should be
installed on your device, example, Gmail.

Example:

Create a new project and give it the name of your choice. Modify the activity_main.xml
file to the following:

<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/email
android:layout_width=fill_parent
android:layout_height=wrap_content
android:text=Compose Email/>
</LinearLayout>

Modify the java class, MainActivity.java to the following:


import android.os.Bundle;
import android.net.Uri;
import android.view.View;
import android.content.Intent;
import android.app.Activity;
import android.util.Log;
import android.widget.Button;
import android.view.Menu;
import android.widget.Toast;

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

Button embtn = (Button) findViewById(R.id.email);
embtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {

composeandSendEmail();
}
});

}
protected void composeandSendEmail () {
Log.i(Send email, );

String[] TO = {mikeartemov@gmail.com};
String[] CC = {test@gmail.com};
Intent eIntent = new Intent(Intent.ACTION_SEND);
eIntent.setData(Uri.parse(mailto:));
eIntent.setType(text/plain);


eIntent.putExtra(Intent.EXTRA_EMAIL, TO);
eIntent.putExtra(Intent.EXTRA_CC, CC);
eIntent.putExtra(Intent.EXTRA_SUBJECT, Add subject);
eIntent.putExtra(Intent.EXTRA_TEXT, Add email message);

try {

startActivity(Intent.createChooser(eIntent, Send mail));


finish();
Log.i(Email has been send, );
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(MainActivity.this,
You have not installed email client., Toast.LENGTH_SHORT).show();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Add items to the action menu if they are available.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}

Modify the contents of the string.xml file to the following, to define constants:

<?xml version=1.0 encoding=utf-8?>
<resources>
<string name=app_name>AndroidSendingEmail</string>

<string name=hello_world>Hello world!</string>


<string name=action_settings>Settings</string>
<string name=email>Compose Email</string>
</resources>

Note that no changes should be made to the AndroidManifest.xml file, so maintain it on its
default state. You can now run your app by selecting the project and clicking onRun
from the toolbar. Select to run the app on the real device from the dialog that will appear.
The following window should appear:


Click on the Compose Email button. All the email clients installed on your device will
be enlisted. Choose the one of your choice. You will then see the fields for filling in the
To email, the Subject, and then another field where you can compose your message. You
can then hit the Send Email button and the email will be sent.

Sending SMS in Android



You might need to use your app to send messages to other people. This can be
implemented in two ways:

1. By the use of SmsManager.
2. By the use of Buit-in Intent.

Using SmsManager

It manages the operations involving the sending of messages to other mobile phones. It is
implemented as follows:

SmsManager manager = SmsManager.getDefault();

We have implemented it by calling the method SmsManager.getDefault() ,which is a static
method. The instantiated object above, that is, manager can then be used to send
messages to the specified mobile number as shown below:

manager.sendTextMessage(phoneNo, null, SMS, null, null);

Other methods which can be applied to the class SmsManager include the following:

1. ArrayList<String> messagedivision (String text)- a single message is divided
into several fragments. No fragment is bigger than the original SMS message.
2. static SmsManager getDefault()
Returns to the user the default instance of SmsManager.

For you to demonstrate sending a Sms text, you need a physical device running android.
otherwise, the emulator might end up failing. You should also target SDK.

Create a new project and give it a name of your choice. Modify the activity_main.xml file
to the following:

<LinearLayout xmlns:android=http://schemas.android.com/apk/res/android
android:layout_width=fill_parent
android:layout_height=fill_parent
android:orientation=vertical >
<TextView
android:id=@+id/mobNo
android:layout_width=wrap_content
android:layout_height=wrap_content

android:text=Enter Phone Number: />


<EditText
android:id=@+id/editmobNo
android:layout_width=fill_parent
android:layout_height=wrap_content
android:inputType=phone/>
<TextView
android:id=@+id/tvMessage
android:layout_width=wrap_content
android:layout_height=wrap_content
android:text=Enter SMS Message />
<EditText
android:id=@+id/edSMS
android:layout_width=fill_parent
android:layout_height=wrap_content
android:inputType=textMultiLine/>
<Button android:id=@+id/btnsendsms
android:layout_width=fill_parent
android:layout_height=wrap_content
android:text=Send SMS />
</LinearLayout>


Modify the java class MainActivity,java to the following:

import android.telephony.SmsManager;
import android.os.Bundle;
import android.view.Menu;
import android.app.Activity;
import android.util.Log;
import android.widget.Button;
import android.widget.Toast;
import android.view.View;
import android.widget.EditText;
public class MainActivity extends Activity {
Button sbtn;
EditText mobNo;
EditText msge;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);


sbtn = (Button) findViewById(R.id.btnsendsms);
mobNo = (EditText) findViewById(R.id.editmobNo);
msge = (EditText) findViewById(R.id.edSMS);

sbtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
sendMessage();
}
});

}
protected void sendMessage() {
Log.i(Send SMS, );

String mobNo = mobNo.getText().toString();
String message = msge.getText().toString();

try {
SmsManager manager = SmsManager.getDefault();
manager.sendTextMessage(mobNo, null, message, null, null);

Toast.makeText(getApplicationContext(), SMS sent.,


Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(getApplicationContext(),
sending failed, please try again.,
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}


The AndroidManifest.xml file should be modified to the following:

<?xml version=1.0 encoding=utf-8?>
<manifest xmlns:android=http://schemas.android.com/apk/res/android

package=com.example.sendsmstext
android:versionCode=1
android:versionName=1.0 >
<uses-sdk
android:minSdkVersion=8
android:targetSdkVersion=17 />
<uses-permission android:name=android.permission.SEND_SMS />
<application
android:allowBackup=true
android:icon=@drawable/ic_launcher
android:label=@string/app_name
android:theme=@style/AppTheme >
<activity
android:name=com.example.sendsmstext.MainActivity
android:label=@string/app_name >
<intent-filter>
<action android:name=android.intent.action.MAIN />
<category android:name=android.intent.category.LAUNCHER />
</intent-filter>
</activity>
</application>

</manifest>

Now that you are finished, its time to run the app. Just connect the device to the computer
using a USB cable. Select the project or open one of its files and click Run from the
toolbar. Select to run the app on the device. The following will be seen:

Make sure that your GSM connection is okay. Enter the phone number of the recipient,
followed by the SMS message itself. Finally, click on the SendSMS button. Your
message will be delivered.

Using Built-in Intent

In this method, ACTION_VIEW is used to launch the SMS client installed on your device.

Intent intent = new Intent(Intent.ACTION_VIEW);

Smsto: and the type of data to be send should also be specified:


intent.setData(Uri.parse(smsto:));
intent.setType(vnd.android-dir/mms-sms);

You can then specify both the phone number and message as follows:

intent.putExtra(address , new String(1123406889;3493694320));
intent.putExtra(sms_body , SMS to Mike);

Note that in the above example, we are sending the SMS to two numbers and we have
used a semi-colon (;) to separate the two. Both the address and the sms_body should
be written in lower case, since they are case sensitive.

Example:

Create a new project and give it a name of your choice. Modify the activity_main.xml file
to the following:

<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/smssend
android:layout_width=fill_parent
android:layout_height=wrap_content
android:text=Compose SMS/>
</LinearLayout>

Modify the MainActivity.xml to the following:

import android.app.Activity;
import android.net.Uri;
import android.util.Log;
import android.os.Bundle;
import android.content.Intent;
import android.view.View;
import android.view.Menu;
import android.widget.Toast;
import android.widget.Button;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

Button sbtn = (Button) findViewById(R.id.smssend);
sbtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
sendSMSText();
}
});

}
protected void sendSMSText() {
Log.i(Send SMS , );

Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(smsto:));
smsIntent.setType(vnd.android-dir/mms-sms);
intent.putExtra(address , new String (7825456929));
intent.putExtra(sms_body , Send SMS to Mike);
try {
startActivity(intent);
finish();

Log.i(SMS has been sent, );


} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(MainActivity.this,
sending SMS has failed, try again., Toast.LENGTH_SHORT).show();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// items are added to the action bar if they are available.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
The NadroidManifest.xml file should be as follows:

<?xml version=1.0 encoding=utf-8?>
<manifest xmlns:android=http://schemas.android.com/apk/res/android
package=com.example.sendsmstext
android:versionCode=1
android:versionName=1.0 >
<uses-sdk

android:minSdkVersion=8
android:targetSdkVersion=17 />
<application
android:allowBackup=true
android:icon=@drawable/ic_launcher
android:label=@string/app_name
android:theme=@style/AppTheme >
<activity
android:name=com.example.sendsmstext.MainActivity
android:label=@string/app_name >
<intent-filter>
<action android:name=android.intent.action.MAIN />
<category android:name=android.intent.category.LAUNCHER />
</intent-filter>
</activity>
</application>
</manifest>

Once you have finished, connect your phone to the computer, select the project and click
Run. Choose to run on the device. The following screen will appear:


Click on the Compose SMS button. You can modify the defaults that will appear. Once
you write the message and the phone number, click on send and the SMS will be sent.

Making Phone Calls



Although you can still make a call with your phone number, you might need to include
this in your app, when needing to call using a hard coded number. In this section, you will
learn how to use intent to make a call. The call functionality is triggered by
ACTION_CALL, so you must use the intent to call it.:

Intent intent = new Intent(Intent.ACTION_CALL);

You can use ACTION_DIAL, instead of the above ACTION_CALL, if you want to be
able to modify the number to be called.

Example:

Create a new project and give it a name of your choice. Modify the activity_main.xml file
to the following:

<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/call
android:layout_width=fill_parent
android:layout_height=wrap_content
android:text=Make Call/>
</LinearLayout>

Modify the class MainActivity.java to the following:

import android.app.Activity;
import android.net.Uri;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.widget.Button;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);
Button btn = (Button) findViewById(R.id.call);
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
phoneCall();
}
});
}
protected void phoneCall() {
Log.i(Make call, );
Intent intent = new Intent(intent.ACTION_CALL);
intent.setData(Uri.parse(tel:0123456789));
try {
startActivity(intent);
finish();
Log.i(call has been made, );
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(MainActivity.this,
failed to call, try again later., Toast.LENGTH_SHORT).show();
}
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Items are added to the action bar if available.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}

The following permissions should be added to the Androidmanifest.xml file:

<?xml version=1.0 encoding=utf-8?>
<manifest xmlns:android=http://schemas.android.com/apk/res/android
package=com.example.phonecallexample
android:versionCode=1
android:versionName=1.0 >
<uses-sdk
android:minSdkVersion=8
android:targetSdkVersion=17 />
<uses-permission android:name=android.permission.CALL_PHONE />
<uses-permission android:name=android.permission.READ_PHONE_STATE />
<application

android:allowBackup=true
android:icon=@drawable/ic_launcher
android:label=@string/app_name
android:theme=@style/AppTheme >
<activity
android:name=com.example.phonecallexample.MainActivity
android:label=@string/app_name >
<intent-filter>
<action android:name=android.intent.action.MAIN />
<category android:name=android.intent.category.LAUNCHER />
</intent-filter>
</activity>
</application>
</manifest>

Now connect the device to your computer. Select the project and then click on Run.
Watch the output on the devices screen. A button written Call 0123456789 will be seen.
Click on it if you wish to be connected, and it will call the mobile number above. The
procedure is very simple.

Android camera

Sometimes, you might need the users of your app to use the existing android from your
app. This is possible to be achieved. To demonstrate this, create a new project and give it a
name of choice. Modify the xml file main_activity.xml to the following:

<RelativeLayout xmlns:android=http://schemas.android.com/apk/res/android
xmlns:tools=http://schemas.android.com/tools
android:layout_width=match_parent
android:layout_height=match_parent
android:paddingBottom=@dimen/activity_vertical_margin
android:paddingLeft=@dimen/activity_horizontal_margin
android:paddingRight=@dimen/activity_horizontal_margin
android:paddingTop=@dimen/activity_vertical_margin
tools:context=.MainActivity>
<ImageView
android:id=@+id/iv1
android:layout_width=match_parent
android:layout_height=match_parent
android:layout_marginLeft=34dp
android:layout_marginTop=36dp

android:contentDescription=Hello world!
android:src=@drawable/ic_launcher />
<TextView
android:id=@+id/tv1
android:layout_width=wrap_content
android:layout_height=wrap_content
android:layout_alignParentTop=true
android:layout_alignRight=@+id/iv1
android:text=Tap the image to open the camera
android:textAppearance=?android:attr/textAppearanceLarge />
</RelativeLayout>

Modify the java class ActivityMain.java to the following:

import android.graphics.Bitmap;
import android.os.Bundle;
import android.content.Intent;
import android.view.Menu;
import android.app.Activity;
import android.view.View.OnClickListener;
import android.view.View;

import android.widget.ImageView;

public class MainActivity extends Activity {

ImageView imgf;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imgf = (ImageView)findViewById(R.id.iv1);
imgf.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
open();
}
});
}
public void open(){
Intent i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(i, 0);

}

@Override
protected void onActivityResult(int reqCode, int resCode, Intent d) {
super.onActivityResult(reqCode, resCode, d);
Bitmap bm = (Bitmap) d.getExtras().get(d);
imgf.setImageBitmap(bm);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}

The AndroidManifext.xml file should be modified to the following:
<?xml version=1.0 encoding=utf-8?>
<manifest xmlns:android=http://schemas.android.com/apk/res/android
package=com.example.cameraexample
android:versionCode=1

android:versionName=1.0 >
<uses-sdk
android:minSdkVersion=8
android:targetSdkVersion=17 />
<application
android:allowBackup=true
android:icon=@drawable/ic_launcher
android:label=@string/app_name
android:theme=@style/AppTheme >
<activity
android:name=com.example.camera.MainActivity
android:label=@string/app_name >
<intent-filter>
<action android:name=android.intent.action.MAIN />
<category android:name=android.intent.category.LAUNCHER />
</intent-filter>
</activity>
</application>
</manifest>

Connect your physical device running android to the computer. Select the project and click

Run from the toolbar. Choose, to run the app on the device. The following output will be
seen:


Tap on the image and the camera will open. You can take any photo using the opened
camera. After capturing a picture, you will be given the option of whether to discard or
keep the picture.

Android Bluetooth

The androids BluetoothAdapter class, makes it possible to create apps that can share data
and files wirelessly. Let us demonstrate this.
Create a new project and give it a name of your choice. Modify the activity_main.xml file
to the following:

<RelativeLayout xmlns:android=http://schemas.android.com/apk/res/android
xmlns:tools=http://schemas.android.com/tools
android:layout_width=match_parent
android:layout_height=match_parent
android:paddingBottom=@dimen/activity_vertical_margin
android:paddingLeft=@dimen/activity_horizontal_margin
android:paddingRight=@dimen/activity_horizontal_margin
android:paddingTop=@dimen/activity_vertical_margin
tools:context=.MainActivity >
<ScrollView
android:id=@+id/sv1
android:layout_width=wrap_content
android:layout_height=wrap_content
android:layout_alignParentBottom=true
android:layout_alignParentLeft=true
android:layout_alignParentRight=true
android:layout_alignParentTop=true >

<LinearLayout
android:layout_width=match_parent
android:layout_height=match_parent

android:orientation=vertical >

<TextView
android:id=@+id/tv1
android:layout_width=wrap_content
android:layout_height=wrap_content
android:text=Bluetooth
android:textAppearance=?android:attr/textAppearanceLarge />

<Button
android:id=@+id/b1
android:layout_width=wrap_content
android:layout_height=wrap_content
android:onClick=on
android:text=Turn On />

<Button
android:id=@+id/b2
android:layout_width=wrap_content
android:layout_height=wrap_content
android:onClick=visible

android:text=Get Visible/>

<Button
android:id=@+id/b3
android:layout_width=wrap_content
android:layout_height=wrap_content
android:onClick=list
android:text=List Devices />

<Button
android:id=@+id/b4
android:layout_width=wrap_content
android:layout_height=wrap_content
android:onClick=off
android:text=Turn Off />

<ListView
android:id=@+id/lv1
android:layout_width=match_parent
android:layout_height=wrap_content
android:visibility=visible >

</ListView>
</LinearLayout>
</ScrollView>
</RelativeLayout>

Modify the MainActivity.java class to the following:

import android.widget.Toast;
import java.util.ArrayList;
import android.app.Activity;
import java.util.List;
import java.util.Set;
import android.os.Bundle;
import android.bluetooth.BluetoothAdapter;
import android.view.View;
import android.bluetooth.BluetoothDevice;
import android.view.Menu;
import android.content.Intent;
import android.widget.ListAdapter;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import android.widget.Button;
public class MainActivity extends Activity {
private BluetoothAdapter bA;
private Button bOn,bOff,Visible,lst;
private Set<BluetoothDevice>pairedDevices;
private ListView lv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bOn = (Button)findViewById(R.id.b1);
bOff = (Button)findViewById(R.id.b2);
Visible = (Button)findViewById(R.id.b3);
lst = (Button)findViewById(R.id.b4);
lv = (ListView)findViewById(R.id.lv1);
bA = BluetoothAdapter.getDefaultAdapter();
}
public void on(View v){
if (!bA.isEnabled()) {
Intent tOn = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(tOn, 0);

Toast.makeText(getApplicationContext(),Turned on
,Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(getApplicationContext(),Already on,
Toast.LENGTH_LONG).show();
}
}
public void list(View v){
pairedDevices = bA.getBondedDevices();
ArrayList lst = new ArrayList();
for(BluetoothDevice b : pairedDevices)
lst.add(b.getName());
Toast.makeText(getApplicationContext(),Showing Paired Devices,
Toast.LENGTH_SHORT).show();
final ArrayAdapter adpt = new ArrayAdapter
(this,android.R.layout.simple_list_item_1, lst);
lv.setAdapter(adpt);
}
public void off(View v){
bA.disable();

Toast.makeText(getApplicationContext(),Turned off ,
Toast.LENGTH_LONG).show();
}
public void visible(View v){
Intent gVisible = new Intent(BluetoothAdapter.
ACTION_REQUEST_DISCOVERABLE);
startActivityForResult(gVisible, 0);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Add items to the action bar if available
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}

Modify the AndroidManifest .xml file to the following:

<?xml version=1.0 encoding=utf-8?>
<manifest xmlns:android=http://schemas.android.com/apk/res/android
package=com.example.bt

android:versionCode=1
android:versionName=1.0 >
<uses-sdk
android:minSdkVersion=8
android:targetSdkVersion=17 />
<uses-permission android:name=android.permission.BLUETOOTH/>
<uses-permission android:name=android.permission.BLUETOOTH_ADMIN/>
<application
android:allowBackup=true
android:icon=@drawable/ic_launcher
android:label=@string/app_name
android:theme=@style/AppTheme >
<activity
android:name=com.example.bt.MainActivity
android:label=@string/application_name >
<intent-filter>
<action android:name=android.intent.action.MAIN />
<category android:name=android.intent.category.LAUNCHER />
</intent-filter>
</activity>
</application>

</manifest>

Now, select the project and click Run. Choose to run on the physical device. The
following screen will be displayed:


Click on the Turn On button, and you will be asked to verify whether you want to turn
on the Bluetooth.


Accept it. Click on the Get Visible button and you will also be asked to verify, whether
you want to make your device discoverable. This will take 120 seconds:


Accept this too. Click on the List Devices button. All paired devices will be displayed
on the Text View. By clicking the Turn Off button, Bluetooth will be turned off.

Conclusion


It can be concluded, that with android programming much can be achieved, by creating
amazing apps. Android programming, is based solely in creating the user interface by
using XML, and java for adding functionality to it.

Java can also be used to create the user interface of an android app, but much more coding
will be needed. Android apps development can be done on ADT, which relies on Eclipse,
or on Android studio, which is based on IntelliJ. Android studio, is the latest development
environment for android, and it supports some features which are not available in the
ADT.

In both cases, one must install the Java Development Tool kit (JDk), or the Java Runtime
Environment (JRE), before installing the IDEs above. After setting them up, one can then
create amazing apps for his own devices and also for sale.