Professional Documents
Culture Documents
Android Programming A Step by Step Guide For Beginners
Android Programming A Step by Step Guide For Beginners
Programming
A Step By Step Guide for Beginners!
Create Your Own Apps!
Kevin Lyn.
Copyright © 2015 by Kevin Lyn.
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
Disclaimer
While all attempts have been made to verify the information provided in this book, the
author doesn’t 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
Normal toasts
Location Based services in Android
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
Definition
Toasts
Notifications
Sending Email
Sending SMS
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
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
Chapter 1:
Definition
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
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
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.
1. Java Development Tool kit (JDK)/ Java Runtime Environment (JRE) – These must
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
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:
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
How to create a Project
For you to be able to create a project in Android, just follow the steps below:
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
Application name- this is the title to be shown on the title bar of the
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
Settings->Applications->Development
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:
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
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.
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:
The android application has many components, all of which can be found in the project.
1. src- by default, it contains a class named “MainActivity.java”. The .java source files for
2. gen- the .R file is contained here, and is responsible for the reference of your project’s
resources.
3. bin- the package files .apk are contained here, and everything else needed to run 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.
Chapter 4:
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:
<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”
<Button android:id=”@+id/btn”
android:layout_width=“wrap_content”
android:layout_height=“wrap_content”
android:text=” a button” />
</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 device’s screen. The text to appear on each
element has also been specified. We have used Linear Layout. We can then load the layout
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.
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
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:
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:
2. EditText- displays the text but the user is able to edit it.
8. ProgressBar- this shows the progress of a task, especially the one running on
the background.
10. Spinner- allows users to select their choice from a drop-down list.
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:
<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”
</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
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
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:
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:
<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”
</LinearLayout>
import android.os.Bundle;
import android.view.View;
import android.app.Activity;
import android.view.Menu;
import android.widget.Button;
import android.widget.TextView;
@Override
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1.setOnClickListener(new View.OnClickListener() {
txtv.setTextSize(14);
});
B2.setOnClickListener(new View.OnClickListener() {
txtv.setTextSize(24);
}
});
@Override
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
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.
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;
@Override
setContentView(R.layout.activity_main);
b1.setOnClickListener(this);
b2.setOnClickListener(this);
if(v.getId() == R.id.btn1)
return;
if(v.getId() == R.id.btn2)
txtv.setTextSize(24);
return;
@Override
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
import android.os.Bundle;
import android.view.Menu;
import android.app.Activity;
import android.widget.Button;
import android.view.View;
import android.widget.TextView;
@Override
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtv.setTextSize(14);
return;
txtv.setTextSize(20);
return;
@Override
getMenuInflater().inflate(R.menu.main, menu);
return true;
The Activity_Main.xml file for this class should be modified 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/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”
</LinearLayout>
In this case, we have specified the handler method via the android:setOnClick attribute in
the layout file.
Chapter 6:
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:
<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>
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;
private Button b;
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
b = (Button) findViewById(R.id.btn);
b.setOnClickListener(new OnClickListener() {
@Override
Toast.makeText(getApplicationContext(),
});
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.
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:
<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>
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;
private Button b;
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
b = (Button) findViewById(R.id.btn);
b.setOnClickListener(new OnClickListener() {
@Override
LayoutInflater in = getLayoutInflater();
View ly = in.inflate(R.layout.custom_toast,
(ViewGroup) findViewById(R.id.advanced_toast));
iv.setImageResource(R.drawable.ic_launcher);
t.setText(“Button is clicked!”);
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:
Notifications
NotificationManager class and getSystemService() method, are also responsible for the
creation of notifications. These three are combined as follows:
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.
<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: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:
<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”
</TextView>
</LinearLayout>
</LinearLayout>
Create another activity called ReceiveActivity and register it with AndroidManfest.mf file.
import android.app.Activity;
import android.os.Bundle;
@Override
super.onCreate(savedInstanceState);
setContentView(R.layout.layout2);
}
Note that in the activity above, we are referring to the layout2 xml file rather than the
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;
@Override
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setContentText(“Subject”).setSmallIcon(R.drawable.icon)
setContentIntent(pIn)
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
2. double getAltitude()- gives the height above sea level in meters, if available.
These are just a few of the available methods, so you can explore the rest and learn how to
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
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 don’t find it, then it has not been installed. Install it.
<android-sdk>/extras/google/google_play_services/libproject/google-play-
services_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, it’s 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.
<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>
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;
GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener
LocationClient mloc;
@Override
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
locbtn.setOnClickListener(new View.OnClickListener() {
displayCurrentLocation();
});
disbtn.setOnClickListener(new V.OnClickListener() {
mLoc.disconnect();
});
conbtn.setOnClickListener(new V.OnClickListener() {
mLoc.connect();
});
@Override
super.onStart();
Loc.connect();
@Override
mLoc.disconnect();
super.onStop();
@Override
@Override
public void onDisconnected() {
Toast.LENGTH_SHORT).show();
@Override
conResult.getErrorCode(),
Toast.LENGTH_SHORT).show();
Double.toString(currLoc.getLatitude()) + “,” +
Double.toString(currLoc.getLongitude());
labelloc.setText(message);
// To show current address on the device’s screen
(new GetAddressTask(this)).execute(currLoc);
/*
This will give the address as per the current latitude and longitude. It is a subclass of
AsyncTask
*/
Context mc;
public GetAddressTask(Context c) {
super();
mc = c;
/*
* the onPostExposure will display the address when the task is *finished.
*/
@Override
@Override
Geocoder gcoder =
Location lc = params[0];
try {
ads = gcoder.getFromLocation(lc.getLatitude(),
lc.getLongitude(), 1);
Log.e(“LocationSampleActivity”,
e1.printStackTrace();
” , ” +
Double.toString(lc.getLongitude()) +
Log.e(“LocationSampleActivity”, errorMessage);
e2.printStackTrace();
return errorString;
Address a = ads.get(0);
/*
*/
a.getMaxAddressLineIndex() > 0 ?
a.getAddressLine(0) : ””,
a.getCountryName());
return aText;
} else {
<resources>
<string name=“app_name”>LocationBasedServicesDemo</string>
<string name=“action_settings”>Settings</string>
</resources>
<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>
</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 don’t 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:
carbon copied.
2. EXTRA_EMAIL- this string holds the email addresses to which the message
should be delivered to.
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
Example:
Create a new project and give it the name of your choice. Modify the activity_main.xml
<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>
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;
@Override
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
embtn.setOnClickListener(new View.OnClickListener() {
});
String[] TO = {“mikeartemov@gmail.com”};
String[] CC = {“test@gmail.com”};
eIntent.setData(Uri.parse(“mailto:”));
eIntent.setType(“text/plain”);
eIntent.putExtra(Intent.EXTRA_EMAIL, TO);
eIntent.putExtra(Intent.EXTRA_CC, CC);
try {
startActivity(Intent.createChooser(eIntent, “Send mail…”));
finish();
Toast.makeText(MainActivity.this,
@Override
getMenuInflater().inflate(R.menu.main, menu);
return true;
Modify the contents of the string.xml file to the following, to define constants:
<resources>
<string name=“app_name”>AndroidSendingEmail</string>
<string name=“hello_world”>Hello world!</string>
<string name=“action_settings”>Settings</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 on“Run”
from the toolbar. Select to run the app on the real device from the dialog that will 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:
Using SmsManager
It manages the operations involving the sending of messages to other mobile phones. It is
implemented as follows:
method. The instantiated object above, that is, “manager” can then be used to send
messages to the specified mobile number as shown below:
Other methods which can be applied to the class SmsManager include the following:
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”
<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”
</LinearLayout>
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;
Button sbtn;
EditText mobNo;
EditText msge;
@Override
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sbtn.setOnClickListener(new View.OnClickListener() {
sendMessage();
});
try {
Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(getApplicationContext(),
Toast.LENGTH_LONG).show();
e.printStackTrace();
@Override
getMenuInflater().inflate(R.menu.main, menu);
return true;
<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>
</intent-filter>
</activity>
</application>
</manifest>
Now that you are finished, it’s 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.
In this method, ACTION_VIEW is used to launch the SMS client installed on your device.
intent.setData(Uri.parse(“smsto:”));
intent.setType(“vnd.android-dir/mms-sms”);
You can then specify both the phone number and message as follows:
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
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>
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;
@Override
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sbtn.setOnClickListener(new View.OnClickListener() {
sendSMSText();
});
intent.setData(Uri.parse(“smsto:”));
smsIntent.setType(“vnd.android-dir/mms-sms”);
try {
startActivity(intent);
finish();
Log.i(“SMS has been sent…”, ””);
Toast.makeText(MainActivity.this,
@Override
getMenuInflater().inflate(R.menu.main, menu);
return true;
<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>
</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
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>
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;
@Override
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn.setOnClickListener(new View.OnClickListener() {
phoneCall();
});
intent.setData(Uri.parse(“tel:0123456789”));
try {
startActivity(intent);
finish();
Toast.makeText(MainActivity.this,
}
@Override
getMenuInflater().inflate(R.menu.main, menu);
return true;
<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” />
<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>
</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 device’s 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
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
<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:textAppearance=”?android:attr/textAppearanceLarge” />
</RelativeLayout>
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;
ImageView imgf;
@Override
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imgf = (ImageView)findViewById(R.id.iv1);
imgf.setOnClickListener(new OnClickListener() {
@Override
open();
});
startActivityForResult(i, 0);
}
@Override
imgf.setImageBitmap(bm);
@Override
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
<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>
</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
Android Bluetooth
The android’s BluetoothAdapter class, makes it possible to create apps that can share data
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”
<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”
<Button
android:id=”@+id/b4”
android:layout_width=“wrap_content”
android:layout_height=“wrap_content”
android:onClick=“off”
<ListView
android:id=”@+id/lv1”
android:layout_width=“match_parent”
android:layout_height=“wrap_content”
android:visibility=“visible” >
</ListView>
</LinearLayout>
</ScrollView>
</RelativeLayout>
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;
private Set<BluetoothDevice>pairedDevices;
@Override
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();
if (!bA.isEnabled()) {
startActivityForResult(tOn, 0);
Toast.makeText(getApplicationContext(),“Turned on”
,Toast.LENGTH_LONG).show();
else{
Toast.makeText(getApplicationContext(),“Already on”,
Toast.LENGTH_LONG).show();
pairedDevices = bA.getBondedDevices();
for(BluetoothDevice b : pairedDevices)
lst.add(b.getName());
Toast.LENGTH_SHORT).show();
(this,android.R.layout.simple_list_item_1, lst);
lv.setAdapter(adpt);
bA.disable();
Toast.makeText(getApplicationContext(),“Turned off” ,
Toast.LENGTH_LONG).show();
ACTION_REQUEST_DISCOVERABLE);
startActivityForResult(gVisible, 0);
@Override
getMenuInflater().inflate(R.menu.main, menu);
return true;
<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>
</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.