Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
47 views

Android Notes Using Java

Android is an open-source, Linux-based operating system used for mobile devices like smartphones and tablets. It was developed by Google and the Open Handset Alliance. The key goals of Android are to further the mobile experience for end users and create a successful real-world product. Some of the major versions of Android include Lollipop, KitKat, Jelly Bean, Ice Cream Sandwich, Froyo, and Donut. Android uses Java as its main programming language and features an open-source codebase, extensive customization options, and access to many mobile applications.

Uploaded by

sahiler485
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
47 views

Android Notes Using Java

Android is an open-source, Linux-based operating system used for mobile devices like smartphones and tablets. It was developed by Google and the Open Handset Alliance. The key goals of Android are to further the mobile experience for end users and create a successful real-world product. Some of the major versions of Android include Lollipop, KitKat, Jelly Bean, Ice Cream Sandwich, Froyo, and Donut. Android uses Java as its main programming language and features an open-source codebase, extensive customization options, and access to many mobile applications.

Uploaded by

sahiler485
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 53

Android

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.

Categories of Android applications

 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.

Version Code name API Level


1.5 Cupcake 3
1.6 Donut 4
2.1 Eclair 7
2.2 Froyo 8
2.3 Gingerbread 9 and 10
3.1 and 3.3 Honeycomb 12 and 13
4.0 Ice Cream Sandwitch 15
4.1, 4.2 and 4.3 Jelly Bean 16, 17 and 18
4.4 KitKat 19
5.0 Lollypop 21
6.0 Marshmallow 23
7.0 Nougat 24-25
8.0 Oreo 26-27
Android Architecture
Android architecture or Android software stack is categorized into five parts:

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

.The core building blocks or fundamental components of android are :

 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.

Intent intent=new Intent(Intent.ACTION_VIEW);


intent.setData(Uri.parse("http://www.google.com"));
startActivity(intent);
4. Service- Service is a background process that can run for a long time. There are two types of
services local and remote. Local service is accessed from within the application whereas remote
service is accessed remotely from other applications running on the same device.

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.

7. AndroidManifest.xml- It contains information about activities, content providers, permissions


etc. It is like the web.xml file in Java EE.

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.

Types of Android Intents

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.

Intent intent=new Intent(Intent.ACTION_VIEW);


intent.setData(Uri.parse("http://www.google.com"));
startActivity(intent);

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.

Intent i = new Intent(getApplicationContext(), ActivityTwo.class);


startActivity(i);

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.

Requirement and recommendations

The Android emulator takes additional requirements beyond the basic system requirement for
Android Studio. These requirements are given below

 SDK Tools 26.1.1 or higher


 64-bit processor
 Windows: CPU with UG (unrestricted guest) support
 HAXM 6.2.1 or later (recommended HAXM 7.2.0 or later)

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.

How to make android apps ?


1. Create the new android project
2. Write the message (optional)
3. Run the android application
Hello Android Example

Step-1 Create the New Android project- For creating the new android studio project:

 Select Start a 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.

 Select the Activity type (Empty Activity).


 Provide the Activity Name and click finish.

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.

<?xml version="1.0" encoding="utf-8"?>


< TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello Android!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />

 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);
}
}

Step-3 Run the android application

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.

1. Java Source - MainActivity.java File


import android.os.Bundle;
import android.app.Activity;
public class MainActivity extends Activity
{
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
 Activity is a java class that creates and default window on the screen where we can place
different components such as Button, EditText, TextView, Spinner etc. It is like the Frame
of Java AWT. It provides life cycle methods for activity such as onCreate, onStop,
OnResume etc.
 The onCreate method is called when Activity class is first created.
 The setContentView(R.layout.activity_main) gives information about our layout resource.
Here, our layout resources are defined in activity_main.xml file.

2. Resources - It contains resource files including activity_main, strings, styles 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

<?xml version="1.0" encoding="utf-8"?>


<resources>
<string name="app_name">helloandroid</string>
<string name="hello_world">Hello world!</string>
<string name="menu settings">Settings</string>
</resources>
You can change the value of the hello_world attribute from this file.
3. Generated R.java file

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

/* AUTO-GENERATED FILE. DO NOT MODIFY. */


public final class R {
public static final class attr { }
public static final class drawable {
public static final int ic_launcher=0x7f020000;
}
public static final class id {
public static final int menu_settings=0x7f070000;
}
public static final class layout {
public static final int activity_main=0x7f030000;
}
public static final class menu {
public static final int activity_main=0x7f060000;
}
public static final class string {
public static final int app_name=0x7f040000;
public static final int hello_world=0x7f040001;
public static final int menu_settings=0x7f040002;
}
public static final class style {
public static final int AppBaseTheme=0x7f050000;
public static final int AppTheme=0x7f050001;
}
}
4. APK File- An apk file is created by the framework automatically. If you want to run the
android application on the mobile, transfer and install it.

5. Manifest file- It contains information about package including components such as


activities, services, content providers etc.

Dalvik Virtual Machine (DVM)

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

Android Button represents a push-button. The android.widget.Button is subclass of TextView class


and CompoundButton is the subclass of Button class. There are different types of buttons in
android such as RadioButton, ToggleButton, CompoundButton etc.

Android Button Example with Listener

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

 calling listener on button or


 adding onClick property of button in activity's xml file.

Method-1
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View view)
{
//code
}
});

Method-2

<Button android:onClick="methodName" />


Drag the component or write the code for UI in activity_main.xml- First of all, drag 2 textfields
from the Text Fields palette and one button from the Form Widgets palette as shown in the
following figure.

The generated code for the UI components will be like this:

File: activity_main.xml

<?xml version="1.0" encoding="utf-8"?>


<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="61dp"
android:ems="10"
android:inputType="number"
tools:layout_editor_absoluteX="84dp"
tools:layout_editor_absoluteY="53dp" />
<EditText
android:id="@+id/editText2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/editText1"
android:layout_centerHorizontal="true"
android:layout_marginTop="32dp"
android:ems="10"
android:inputType="number"
tools:layout_editor_absoluteX="84dp"
tools:layout_editor_absoluteY="127dp" />

<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" />

2. Activity class ( File: MainActivity.java)

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

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.

Android Activity Lifecycle methods

Method Description

onCreate called when activity is first created.

onStart called when activity is becoming visible to the user.

onResume called when activity will start interacting with the user.

onPause called when activity is not visible to the user.

OnStop called when activity is no longer visible to the user.

onRestart called after your activity is stopped, prior to start.

onDestroy called before the activity is destroyed.


Android Fragments

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.

Android Fragment Lifecycle

The lifecycle of android fragment is like the activity lifecycle. There are 12 lifecycle methods for
fragment.
No. Method Description

1) onAttach(Activity) it is called only once when it is attached with activity.

2) onCreate(Bundle) It is used to initialize the fragment.

3) onCreateView(LayoutInflater, creates and returns view hierarchy.


ViewGroup, Bundle)

4) onActivityCreated(Bundle) It is invoked after the completion of onCreate() method.

5) onViewStateRestored(Bundle) It provides information to the fragment that all the saved state of
fragment view hierarchy has been restored.

6) onStart() makes the fragment visible.

7) onResume() makes the fragment interactive.

8) onPause() is called when fragment is no longer interactive.

9) onStop() is called when fragment is no longer visible.

10) onDestroyView() allows the fragment to clean up resources.

11) onDestroy() allows the fragment to do final clean up of fragment state.

12) onDetach() It is called immediately prior to the fragment no longer being


associated with its activity.
Android Menu

Android Option Menu Example

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;
}

public boolean onOptionsItemSelected(MenuItem item)


{
int id = item.getItemId();
switch (id)
{
case R.id.item1:
Toast.makeText(getApplicationContext(),"Item 1 Selected",Toast.LENGTH_LONG).show();
return true;
case R.id.item2:
Toast.makeText(getApplicationContext(),"Item 2 Selected",Toast.LENGTH_LONG).show();
return true;
case R.id.item3:
Toast.makeText(getApplicationContext(),"Item 3 Selected",Toast.LENGTH_LONG).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
} }
Output after clicking on the first menu item .
Android Service

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.

Life Cycle of Android Service

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;
}
}
}

4. Declare the Service in the AndroidManifest.xml file

Finally, declare the service in the manifest file.

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;

public class NextPage extends Activity {

@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

The android.database.sqlite.SQLiteOpenHelper class is used for database creation and version


management. For performing any database operation, you have to provide the implementation
of onCreate() and onUpgrade() methods of SQLiteOpenHelper class. There are two constructors
of SQLiteOpenHelper class.

Constructor Description

SQLiteOpenHelper(Context context, String name, creates an object for creating, opening


SQLiteDatabase.CursorFactory factory, int version) and managing the database.

SQLiteOpenHelper(Context context, String name, creates an object for creating, opening


SQLiteDatabase.CursorFactory factory, int version, and managing the database. It specifies
DatabaseErrorHandler errorHandler) the error handler.

Methods of SQLiteOpenHelper class

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 synchronized void close () closes the database object.

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.

Methods of SQLiteDatabase class

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.

int update(String table, ContentValues updates a row.


values, String whereClause, String[]
whereArgs)

Cursor query(String table, String[] returns a cursor over the resultset.


columns, String selection, String[]
selectionArgs, String groupBy, String
having, String orderBy)
Android Media Player Example

We can play and control the audio files in android by the help of MediaPlayer class

MediaPlayer class

The android.media.MediaPlayer class is used to control the audio or video files.

Methods of MediaPlayer class

Method Description

public void setDataSource(String path) sets the data source (file path or http url) to use.

public void prepare() prepares the player for playback synchronously.

public void start() it starts or resumes the playback.

public void stop() it stops the playback.

public void pause() it pauses the playback.

public boolean isPlaying() checks if media player is playing.

public void seekTo(int millis) seeks to specified time in miliseconds.

public void setLooping(boolean looping) sets the player for looping or non-looping.

public boolean isLooping() checks if the player is looping or non-looping.

public void selectTrack(int index) it selects a track for the specified index.

public int getCurrentPosition() returns the current playback position.

public int getDuration() returns duration of the file.


public void setVolume(float leftVolume,float rightVolume) sets the volume on this player.

Android MediaPlayer Example of controlling the audio

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.

Advantages of JSON over XML

1) JSON is faster and easier than xml for AJAX applications.


2) Unlike XML, it is shorter and quicker to read and write.
3) It uses 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

The [ (square bracket) represents the json array.


["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]

Let's take another example of 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.

Constructor of TextToSpeech class


TextToSpeech(Context context, TextToSpeech.OnInitListener)

Methods of TextToSpeech class

The commonly used methods of TextToSpeech class are as follows:

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 setSpeechRate(float speed) it sets the speed for the speech.

int setPitch(float speed) it sets the pitch for the speech.

int setLanguage (Locale loc) it sets the locale specific language for the speech.

void shutdown() it releases the resource set by TextToSpeech Engine.

int stop() it interrupts the current utterance (whether played or rendered to file)
and discards other utterances in the queue.

TextToSpeech.OnInitListener Interface

You need to implement TextToSpeech.OnInitListener interface, for performing event handling on


TextToSpeech engine.

Method of TextToSpeech.OnInitListener Interface

There is only one method in this interface.


Method Description

void onInit (int Called to signal the completion of the TextToSpeech engine initialization. The
status) status can be SUCCESS or ERROR.

Android TextToSpeech Example

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

How to make a phone call in android?

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.

Intent callIntent = new Intent(Intent.ACTION_CALL);


callIntent.setData(Uri.parse("tel:"+8802177690));//change the number
startActivity(callIntent);

Android Google Map


Android provides facility to integrate Google map in our application. Google map displays your
current location, navigate location direction, search location etc. We can also customize Google
map according to our requirement.

Types of Google Maps

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);

Methods of Google map

Google map API provides several methods that help to customize Google map. These methods are
as following:

Methods Description

addCircle(CircleOptions options) This method add circle to map.

addPolygon(PolygonOptions options) This method add polygon to map.

addTileOverlay(TileOverlayOptions options) This method add tile overlay to the map.

animateCamera(CameraUpdate update) This method moves the map according to the update with an
animation.

clear() This method removes everything from the map.

getMyLocation() This method returns the currently displayed user location.

moveCamera(CameraUpdate update) This method reposition the camera according to the instructions
defined in the update.

setTrafficEnabled(boolean enabled) This method set the traffic layer on or off.

snapshot(GoogleMap.SnapshotReadyCallback This method takes a snapshot of the map.


callback)

stopAnimation() This method stops the camera animation if there is any progress.

You might also like