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.
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
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.
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.
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: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.
12. TimePicker- users are able to select time in either AM/PM or 24 hour format.
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.
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
});
}
@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.
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.
}
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) {
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
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>
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.
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 {
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.
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
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);
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();
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.
<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.