Android Notes Using Java
Android Notes Using Java
Android is a software package and linux based operating system for mobile devices such as tablet
computers and smartphones. It is developed by Google and later the OHA (Open Handset Alliance).
Java language is mainly used to write the android code even though other languages can be used. The
goal of android project is to create a successful real-world product that improves the mobile experience
for end users. There are many code names of android such as Lollipop, Kitkat, Jelly Bean, Ice cream
Sandwich, Froyo, Ecliar, Donut etc
Features of Android
It is open-source.
Anyone can customize the Android Platform.
There are a lot of mobile applications that can be chosen by the consumer.
It provides many interesting features like weather details, opening screen, live RSS (Really
Simple Syndication) feeds etc.
It provides support for messaging services(SMS and MMS), web browser, storage
(SQLite), connectivity (GSM, CDMA, Blue Tooth, Wi-Fi etc.), media, handset layout etc.
History of Android
The history and versions of android are interesting to know. The code names of android ranges
from A to J currently, such as Aestro, Blender, Cupcake, Donut, Eclair, Froyo, Gingerbread,
Honeycomb, Ice Cream Sandwitch, Jelly Bean, KitKat and Lollipop.
Initially, Andy Rubin founded Android Incorporation in Palo Alto, California, United
States in October, 2003.
In 17th August 2005, Google acquired android Incorporation. Since then, it is in the
subsidiary of Google Incorporation.
The key employees of Android Incorporation are Andy Rubin, Rich Miner, Chris
White and Nick Sears.
Originally intended for camera but shifted to smart phones later because of low market for
camera only.
Android is the nick name of Andy Rubin given by coworkers because of his love to robots.
In 2007, Google announces the development of android OS.
In 2008, HTC launched the first android mobile.
Entertainment
Tools
Communication
Productivity and Personalization
Music and Audio
Media and Video,Travel and Local etc.
Android Versions, Codename and API
The following table shows the android versions, codenames and API Level provided by Google.
1. linux kernel
2. native libraries (middleware),
3. Android Runtime
4. Application Framework
5. Applications
1) Linux kernel -It is the heart of android architecture that exists at the root of android
architecture. Linux kernel is responsible for device drivers, power management, memory
management, device management and resource access.
2) Native Libraries- On the top of linux kernel, their are Native libraries such as WebKit,
OpenGL, FreeType, SQLite, Media, C runtime library (libc) etc. The WebKit library is responsible
for browser support, SQLite is for database, FreeType for font support, Media for playing and
recording audio and video formats.
3) Android Runtime- In android runtime, there are core libraries and DVM (Dalvik Virtual
Machine) which is responsible to run android application. DVM is like JVM but it is optimized
for mobile devices. It consumes less memory and provides fast performance.
4) Android Framework - On the top of Native libraries and android runtime, there is android
framework. Android framework includes Android API's such as UI (User Interface), telephony,
resources, locations, Content Providers (data) and package managers. It provides a lot of classes
and interfaces for android application development.
5) Applications- On the top of android framework, there are applications. All applications such
as home, contact, settings, games, browsers are using android framework that uses android runtime
and libraries. Android runtime and native libraries are using linux kernal.
Android Core Building Blocks
Activities
Views
Intents
Services
Content providers
Fragments and
AndroidManifest.xml
1. Activity - An activity is a class that represents a single screen. It is like a Frame in AWT.
2. View -A view is the UI element such as button, label, textfield etc. Anything you see is a view.
3. Intent- Intent is used to invoke components. It is mainly used to Start the service, Launch an
activity, Display a web page, Display a list of contacts, Broadcast a message, Dial a phone call etc.
For example, you may write the following code to view the webpage.
5. Content Provider- Content Providers are used to share data between the applications.
6. Fragment- Fragments are like parts of activity. An activity can display one or more fragments
on the screen at the same time.
8. Android Virtual Device (AVD)- It is used to test the android application without the need for
mobile or tablet etc. It can be created in different configurations to emulate different types of real
devices.
Intent
Android Intent is the message that is passed between components such as activities, content
providers, broadcast receivers, services etc. It is generally used with startActivity() method to
invoke activity, broadcast receivers etc. The dictionary meaning of intent is intention or purpose.
So, it can be described as the intention to do action. The LabeledIntent is the subclass of
android.content.Intent class.
Intent is used to invoke components. It is mainly used to: Start the service, Launch an activity,
Display a web page, Display a list of contacts, Broadcast a message ,Dial a phone call etc.For
example, you may write the following code to view the webpage.
1) Implicit Intent
2) Explicit Intent
1) Implicit Intent
Implicit Intent doesn't specifiy the component. In such case, intent provides information of
available components provided by the system that is to be invoked. For example, you may write
the following code to view the webpage.
2) Explicit Intent
Explicit Intent specifies the component. In such case, intent provides the external class to be
invoked. Android Explicit intent specifies the component to be invoked from activity. In other
words, we can call another activity in android by explicit intent. We can also pass the information
from one activity to another using explicit intent.
Android Emulator
The Android emulator is an Android Virtual Device (AVD), which represents a specific Android
device. We can use the Android emulator as a target device to execute and test our Android
application on our PC. The Android emulator provides almost all the functionality of a real device.
We can get the incoming phone calls and text messages. It also gives the location of the device
and simulates different network speeds. Android emulator simulates rotation and other hardware
sensors. It accesses the Google Play store, and much more.
Testing Android applications on emulator are sometimes faster and easier than doing on a real
device. For example, we can transfer data faster to the emulator than to a real device connected
through USB.The Android emulator comes with predefined configurations for several Android
phones, Wear OS, tablet, Android TV devices.
The Android emulator takes additional requirements beyond the basic system requirement for
Android Studio. These requirements are given below
The Android emulator is installed while installing the Android Studio. However some components
of emulator may or may not be installed while installing Android Studio. To install the emulator
component, select the Android Emulator component in the SDK Tools tab of the SDK Manager.
Step-1 Create the New Android project- For creating the new android studio project:
Provide the following information: Application name, Company domain, Project location
and Package name of application and click next.
Select the API level of application and click next.
After finishing the Activity configuration, Android Studio auto generates the activity class and
other required configuration files. Now an android project has been created. You can explore the
android project and see the simple program, it looks like this:
Step-2 Write the text message
File: activity_main.xml- Android studio auto generates code for activity_main.xml file.
You may edit this file according to your requirement.
File: MainActivity.java
import android.app.Activity;
import android.os.Bundle;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
To run the android application, click the run icon on the toolbar or simply press Shift + F10.
The android emulator might take 2 or 3 minutes to boot. So please have patience. After booting
the emulator, the android studio installs the application and launches the activity. You will see
something like this:
Internal Details of Hello Android Example
Android application contains different components such as java source code, string resources,
images, manifest file, apk file etc.
File: activity_main.xml
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="@string/hello_world" />
A textview is created by the framework automatically. But the message for this string is defined
in the strings.xml file. The @string/hello_world provides information about the textview message.
The value of the attribute hello_world is defined in the strings.xml file.
File: strings.xml
It is the auto-generated file that contains IDs for all the resources of res directory. It is generated
by aapt(Android Asset Packaging Tool). Whenever you create any component on activity_main,
a corresponding ID is created in the R.java file which can be used in the Java Source file later.
File: R.java
As we know the modern JVM is high performance and provides excellent memory management.
But it needs to be optimized for low-powered handheld devices as well.The Dalvik Virtual
Machine (DVM) is an android virtual machine optimized for mobile devices. It optimizes the
virtual machine for memory, battery life and performance.Dalvik is a name of a town in Iceland.
The Dalvik VM was written by Dan Bornstein.The Dex compiler converts the class files into the
.dex file that run on the Dalvik VM. Multiple class files are converted into one dex file.
Android Widgets
There are a lot of android widgets such as Button, EditText, AutoCompleteTextView,
ToggleButton, DatePicker, TimePicker, ProgressBar etc. The widely used android widgets are
given below:
Android Button
Android Toast- Displays information for the short duration of time. Custom Toast-We are
able to customize the toast, such as we can display image on the toast
ToggleButton-It has two states ON/OFF.
CheckBox
AlertDialog displays a alert dialog containing the message with OK and Cancel buttons.
Spinner
Spinner displays the multiple options, but only one can be selected at a time.
AutoCompleteTextView
RatingBar- RatingBar displays the rating bar.
DatePicker- Datepicker displays the datepicker dialog that can be used to pick the date.
TimePicker-TimePicker displays the timepicker dialog that can be used to pick the time.
ProgressBar- ProgressBar displays progress task.
Android Widgets Example
Example - Android Button
Here, we are going to create two textfields and one button for sum of two numbers. If user clicks
button, sum of two input values is displayed on the Toast. We can perform action on button using
different types such as
Method-1
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View view)
{
//code
}
});
Method-2
File: activity_main.xml
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/editText2"
android:layout_centerHorizontal="true"
android:layout_marginTop="109dp"
android:text="ADD"
tools:layout_editor_absoluteX="148dp"
tools:layout_editor_absoluteY="266dp" />
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
private EditText e1, e2;
private Button b1;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addListenerOnButton();
}
public void addListenerOnButton()
{
e1 = (EditText) findViewById(R.id.editText1);
e2 = (EditText) findViewById(R.id.editText2);
b1 = (Button) findViewById(R.id.button);
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view){
String value1=e1.getText().toString();
String value2=e2.getText().toString();
int a=Integer.parseInt(value1);
int b=Integer.parseInt(value2);
int sum=a+b;
Toast.makeText(getApplicationContext(),String.valueOf(sum), Toast.LENGTH_LONG).show();
} });
}}
Output:
Android Activity
Android Activity Lifecycle is controlled by 7 methods of android.app. Activity class. The android
Activity is the subclass of ContextThemeWrapper class. An activity is the single screen in android.
It is like window or frame of Java. By the help of activity, you can place all your UI components
or widgets in a single screen.
Method Description
onResume called when activity will start interacting with the user.
Android Fragment is the part of activity, it is also known as sub-activity. There can be more than
one fragment in an activity. Fragments represent multiple screen inside one activity. Android
fragment lifecycle is affected by activity lifecycle because fragments are included in activity. Each
fragment has its own life cycle methods that is affected by activity life cycle because fragments
are embedded in activity. The FragmentManager class is responsible to make interaction between
fragment objects.
The lifecycle of android fragment is like the activity lifecycle. There are 12 lifecycle methods for
fragment.
No. Method Description
5) onViewStateRestored(Bundle) It provides information to the fragment that all the saved state of
fragment view hierarchy has been restored.
Android Option Menus are the primary menus of android. They can be used for settings, search,
delete item etc. Here, we are inflating the menu by calling the inflate() method
of MenuInflater class. To perform event handling on menu items, you need to
override onOptionsItemSelected() method of Activity class.
1. activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="@style/AppTheme.PopupOverlay" />
2. File: context_main.xml
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:text="Hello World!" />
3 menu_main.xml
It contains three items as show below. It is created automatically inside the res/menu directory.
File: menu_main.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context="example.optionmenu.MainActivity">
<item android:id="@+id/item1"
android:title="Item 1"/>
<item android:id="@+id/item2"
android:title="Item 2"/>
<item android:id="@+id/item3"
android:title="Item 3"
app:showAsAction="withText"/>
</menu>
4. Activity class
This class displays the content of menu.xml file and performs event handling on clicking the menu
items.
File: MainActivity.java
import android.os.Bundle;
import android.app.Activity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity
{
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
Android service is a component that is used to perform operations on the background such as
playing music, handle network transactions, interacting content providers etc. It doesn't has any
UI (user interface). The service runs in the background indefinitely even if application is
destroyed..Moreover, service can be bounded by a component to perform interactivity and inter
process communication (IPC).The android.app.Service is subclass of ContextWrapper class.
There can be two forms of a service.The lifecycle of service can follow two different paths: started
or bound.
1. Started
2. Bound
1) Started Service
A service is started when component (like activity) calls startService() method, now it runs in the
background indefinitely. It is stopped by stopService() method. The service can stop itself by
calling the stopSelf() method.
2) Bound Service
A service is bound when another component (e.g. client) calls bindService() method. The client
can unbind the service by calling the unbindService() method.The service cannot be stopped until
all clients unbind the service.
Understanding Started and Bound Service by background music example
Suppose, I want to play music in the background, so call startService() method. But I want to get
information of the current song being played, I will bind the service that provides information
about the current song.
Android Service Example
Let's see the example of service in android that plays an audio in the background. Audio will not
be stopped even if you switch to another activity. To stop the audio, you need to stop the service.
Drag two buttons from the pallete, now the activity_main.xml will look like this:
1. File: activity_main.xml
<Button
android:id="@+id/buttonStart"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="74dp"
android:text="Start Service" />
<Button
android:id="@+id/buttonStop"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="Stop Service" />
<Button
android:id="@+id/buttonNext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="63dp"
android:text="Next Page" />
2. Service class
Now create the service implemenation class by inheriting the Service class and overridding its
callback methods.
File: MyService.java
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.widget.Toast;
public class MyService extends Service
{
MediaPlayer myPlayer;
public IBinder onBind(Intent intent)
{
return null;
}
public void onCreate()
{
Toast.makeText(this, "Service Created", Toast.LENGTH_LONG).show();
myPlayer = MediaPlayer.create(this, R.raw.sun);
myPlayer.setLooping(false); // Set looping
}
public void onStart(Intent intent, int startid)
{
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
myPlayer.start();
}
public void onDestroy() {
Toast.makeText(this, "Service Stopped", Toast.LENGTH_LONG).show();
myPlayer.stop();
} }
3. Activity class
Now create the MainActivity class to perform event handling. Here, we are writing the code to
start and stop service. Additionally, calling the second activity on buttonNext.
File: MainActivity.java
import android.content.Intent;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity implements View.OnClickListener
{
Button buttonStart, buttonStop, buttonNext;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonStart = findViewById(R.id.buttonStart);
buttonStop = findViewById(R.id.buttonStop);
buttonNext = findViewById(R.id.buttonNext);
buttonStart.setOnClickListener(this);
buttonStop.setOnClickListener(this);
buttonNext.setOnClickListener(this);
}
public void onClick(View src)
{
switch (src.getId())
{
case R.id.buttonStart:
startService(new Intent(this, MyService.class));
break;
case R.id.buttonStop:
stopService(new Intent(this, MyService.class));
break;
case R.id.buttonNext:
Intent intent=new Intent(this,NextPage.class);
startActivity(intent);
break;
}
}
}
File: AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="example.androidservice">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".MyService"
android:enabled="true" />
</application>
</manifest>
5. NextPage class
File: NextPage.java
import android.app.Activity;
import android.os.Bundle;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_next);
}
}
Android SQLite
SQLite is an open-source relational database i.e. used to perform database operations on android
devices such as storing, manipulating or retrieving persistent data from the database. It is
embedded in android by default. So, there is no need to perform any database setup or
administration task. SQLiteOpenHelper class provides the functionality to use the SQLite
database.
SQLiteOpenHelper class
Constructor Description
Method Description
public abstract void onCreate(SQLiteDatabase db) called only once when database is created
for the first time.
public abstract void onUpgrade(SQLiteDatabase db, int called when database needs to be upgraded.
oldVersion, int newVersion)
public void onDowngrade(SQLiteDatabase db, int oldVersion, int called when database needs to be
newVersion) downgraded.
SQLiteDatabase class
It contains methods to be performed on sqlite database such as create, update, delete, select etc.
Method Description
void execSQL(String sql) executes the sql query not select query.
long insert(String table, String inserts a record on the database. The table specifies the table name,
nullColumnHack, ContentValues values) nullColumnHack doesn't allow completely null values. If second
argument is null, android will store null values if values are empty.
The third argument specifies the values to be stored.
We can play and control the audio files in android by the help of MediaPlayer class
MediaPlayer class
Method Description
public void setDataSource(String path) sets the data source (file path or http url) to use.
public void setLooping(boolean looping) sets the player for looping or non-looping.
public void selectTrack(int index) it selects a track for the specified index.
Let's see a simple example to start, stop and pause the audio play.
activity_main.xml
1. Drag three buttons from pallete to start, stop and pause the audio play. Now the xml
file will look like this:
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginTop="30dp"
android:text="Audio Controller" />
<Button
android:id="@+id/button1"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView1"
android:layout_below="@+id/textView1"
android:layout_marginTop="48dp"
android:text="start" />
<Button
android:id="@+id/button2"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="@+id/button1"
android:layout_toRightOf="@+id/button1"
android:text="pause" />
<Button
android:id="@+id/button3"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="@+id/button2"
android:layout_toRightOf="@+id/button2"
android:text="stop" />
2. Activity class (MainActivity.java) Let's write the code to start, pause and stop the audio
player.
import android.media.MediaPlayer;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity {
Button start, pause, stop;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
start=(Button)findViewById(R.id.button1);
pause=(Button)findViewById(R.id.button2);
stop=(Button)findViewById(R.id.button3);
final MediaPlayer mp=new MediaPlayer();
try{
mp.setDataSource(Environment.getExternalStorageDirectory().getPath()+"/Music/maine.mp3");
mp.prepare(); }
catch(Exception e) { e.printStackTrace(); }
start.setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
mp.start();
}
});
pause.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mp.pause();
}
});
stop.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mp.stop();
}
});
}
}
Output:
JSON Parser
JSON (Javascript Object Notation) is a programming language . It is minimal, textual, and a subset
of JavaScript. It is an alternative to XML. Android provides support to parse the JSON object and
array.
JSON object
A JSON object contains key/value pairs like map. The keys are strings and the values are the JSON
types. Keys and values are separated by comma. The { (curly brace) represents the json object.
{
"employee":
{
"name": "sachin",
"salary": 56000,
"married": true
}
}
JSON array
{ "Employee" :
[
{"id":"101","name":"Amit","salary":"50000"},
{"id":"102","name":"Deepak","salary":"60000"}
]
}
Example of android JSON parsing
1. activity_main.xml
Drag one textview from the pallete. Now the activity_main.xml file will look like this:
File: activity_main.xml
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="75dp"
android:layout_marginTop="46dp"
android:text="TextView" />
2. Activity class
Let's write the code to parse the xml using DOM parser.
File: MainActivity.java
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends Activity {
public static final String JSON_STRING="{\"employee\":{\"name\":\"Sachin\",\"salary\":56000}}";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView textView1=(TextView)findViewById(R.id.textView1);
try{
JSONObject emp=(new JSONObject(JSON_STRING)).getJSONObject("employee");
String empname=emp.getString("name");
int empsalary=emp.getInt("salary");
String str="Employee Name:"+empname+"\n"+"Employee Salary:"+empsalary;
textView1.setText(str);
}catch (Exception e) {e.printStackTrace();}
}
}
Output:
Android Speech
In android, you can convert your text into speech by the help of TextToSpeech class.
Method Description
int speak (String text, int converts the text into speech. Queue Mode may be QUEUE_ADD or
queueMode, QUEUE_FLUSH. Request parameters can be null,
HashMap params) KEY_PARAM_STREAM, KEY_PARAM_VALUME etc.
int setLanguage (Locale loc) it sets the locale specific language for the speech.
int stop() it interrupts the current utterance (whether played or rendered to file)
and discards other utterances in the queue.
TextToSpeech.OnInitListener Interface
void onInit (int Called to signal the completion of the TextToSpeech engine initialization. The
status) status can be SUCCESS or ERROR.
Let's write the code to convert text into voice. Drag one textview, one edittext and one button for
the layout. Now the activity_main.xml file will look like this:
1. File: activity_main.xml
<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="77dp"
android:layout_marginTop="42dp"
android:ems="10" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/editText1"
android:layout_below="@+id/editText1"
android:layout_marginLeft="59dp"
android:layout_marginTop="39dp"
android:text="Speak" />
2. Activity class
File: MainActivity.java
import android.os.Bundle;
import android.app.Activity;
import java.util.Locale;
import android.speech.tts.TextToSpeech;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity {
private TextToSpeech tts;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EditText e1 = (EditText) findViewById(R.id.editText1);
Button b1 = (Button) findViewById(R.id.button1);
b1.setOnClickListener (new View.OnClickListener() {
public void onClick(View view) {
tts = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener( ) {
public void onInit(int i) {
if( i==TextToSpeech.SUCCESS) {
tts.setLanguage(Locale.US);
tts.setSpeechRate(1.0f);
tts.speak(e1.getText().toString(),TextToSpeech.QUEUE_ADD, null );
}
}
});
}
});
Android Telephony
We are able to make a phone call in android via intent. You need to write only three lines of code
tog make a phone call.
There are four different types of Google maps, as well as an optional to no map at all. Each of
them gives different view on map. These maps are as follow:
1. Normal: This type of map displays typical road map, natural features like river and some features
build by humans.
2. Hybrid: This type of map displays satellite photograph data with typical road maps. It also displays
road and feature labels.
3. Satellite: Satellite type displays satellite photograph data, but doesn't display road and feature
labels.
4. Terrain: This type displays photographic data. This includes colors, contour lines and labels and
perspective shading.
5. None: This type displays an empty grid with no tiles loaded.
Syntax of different types of map
1. googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
2. googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
3. googleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
4. googleMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
Google map API provides several methods that help to customize Google map. These methods are
as following:
Methods Description
animateCamera(CameraUpdate update) This method moves the map according to the update with an
animation.
moveCamera(CameraUpdate update) This method reposition the camera according to the instructions
defined in the update.
stopAnimation() This method stops the camera animation if there is any progress.