0% found this document useful (0 votes)
224 views

Android Notes

1. Future smartphones may have augmented reality capabilities, flexible screens that can fold and project from both sides, and built-in projectors to project content onto surfaces without needing an external display. 2. They may also have seamless voice control, 3D and holographic screens, and even mind control interfaces to operate the device with thoughts. 3. Additional potential features include over-the-air charging without wires, stretchable screens that expand in size, customizable colors by changing LED lights, and dual OLED/e-ink displays for reading.

Uploaded by

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

Android Notes

1. Future smartphones may have augmented reality capabilities, flexible screens that can fold and project from both sides, and built-in projectors to project content onto surfaces without needing an external display. 2. They may also have seamless voice control, 3D and holographic screens, and even mind control interfaces to operate the device with thoughts. 3. Additional potential features include over-the-air charging without wires, stretchable screens that expand in size, customizable colors by changing LED lights, and dual OLED/e-ink displays for reading.

Uploaded by

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

Future Smartphones:-

1. Augmented Reality (AR)


•The term ‘augmented reality‘ or AR when used in the context of
computer technology refers to what we perceive through our senses
(usually sight) enhanced through the use of computer-generated sensory
input such as sound, video, graphics and GPS data.
•Simply put, AR makes available more information for us users by
combining computer data to what we see in real life.
•Using the camera on your phone, you can point it somewhere ‘live’ to
get an information overlay of where you can find the nearest cafes or
dining places, for example.
•Smartphones being portable serve as a good platform for AR to work.
You can just whip out your phone to get the latest and relevant info for
what you are searching for – information which you would otherwise have
to call and ask or search online before heading out of Wi-Fi coverage.
Most AR apps available now utilize some form of Global Positioning
System (GPS) to facilitate location searches and this feature is likely to
develop further over the next couple of years because of its potential.
2. Flexible Screens

• It may soon be the case where smartphones are


able provide a large screen to watch and play
your favourite movies and games while
maintaining a pocketable size.
• Screens can be folded and unfolded, all thanks to
Organic Light-Emitting Diode (OLED) technology.
• This paper-thin screen can even project future-
features-smart-phones/ from both sides of the
screen, so you can show pictures or videos to
your friend on one side while using the other as a
control.
3. In-Built Projector

• If flexible screens are not enough to compensate for the small


screens on smartphones why not integrate a projector within?
• Samsung Galaxy Beam was released back in the second half of
2010. It features a built-in DLP (Digital Light Projection) WVGA
projector that is able to project future-features-smart-phones/ at
up to 50 inches in size at 15 lumens.
• What good will this do? Well, for one thing, future smartphones can
actually be turned into an interactive gaming consoles without a
need for a TV screen; all you’ll need is a flat surface.
• Instead of a physical controller, you can use your body or your
voice. Similar to Kinect, a smart camera and a voice control function
can capture your movements and voice commands to let you
interact with objects and future-features-smart-phones/ on the
projected screen.
4. Seamless Voice Control

• Voice control has been receiving much


attention since Siri made headlines.
• Voice control has existed in many earlier
mobile phones even though the voice
recognition function was crude at best.
• Research has been made to advance the
development of voice control
5. 3D Screens & Holograms

• Smartphones may have already reached the peak for


their screen resolution with Apple’s ‘Retina Display‘,
which actually provides a resolution that is sharper than
what the human eye can perceive.
• Yet, even then, we still want more. Mobile companies
are now moving from 2D future-features-smart-phones/
to 3D future-features-smart-phones/ for the
smartphone screen.
• At present, we have a couple of 3D smartphones in the
market, such as the LG Optimus 3D, the Motorola MT810
as well as the very first Samsung AMOLED 3D. So what
happens after 3D?
6. Mind control
 Back in the day, the main way of using a phone was a physical
keypad. This was eventually replaced by the touchscreens we
use today. With services like Google Assistant and Samsung
Bixby, we can now interact with our devices just by using our
voices.
 I think the next step in this evolution is mind control. The
technology would allow you to perform every task you can do
via touch or voice with your mind.
7. Over-the-air charging
 Let’s face it: the battery life of the average smartphone sucks.
Even if you have a high-end phone like the Mate 20 Pro with
its massive 4,200mAh battery, you’re still only looking at
around two days of average use. Once the device runs out of
juice, you either have to plug it in for a couple of hours or
place it on a wireless charging pad, if your phone supports it.
 Things could be quite different in the future. A company
called Energous is developing technology to charge devices
over the air.
 Place your phone within three feet of the WattUp Mid Field
transmitter and it will start charging right away.
8. Stretchable phones

 The next big thing in display technology in the near


future seems to be flexible displays. We recently saw the
first foldable phone, the Royole FlexPai, and we expect
many more from companies like Samsung, LG, and
Huawei.
 Instead of unfolding a phone for more screen like with
the FlexPai, you’d stretch it out to increase its size, sort of
like a rubber band. All you’d have to do is pull the phone
from two of its corners diagonally.
9. Changing colors

 Phones come in a variety of colors and choosing the best one can
often be a struggle. Black, silver, and white give off a more classic
vibe, but they’re also boring. Red, green, or purple colorways stand
out more, but can give devices a toyish, less professional look. With
smartphones of the future, you may not have to choose anymore.
 Imagine a phone with a completely transparent back made from a
glass-like material that fully absorbs light. The device would have
one or more LED lights inside, the color of which you could change
in the settings of the phone (or maybe with your mind!). When you
choose orange, the entire back cover would completely absorb the
color of the light and look exactly the same, almost as if it were
painted on.
10. OLED and E-ink in one
 OLED displays are great for watching videos and playing games, but they
aren’t the best for reading.
 E-ink displays like those in Amazon’s Kindle e-readers are a much better
option. I’ve been using a Kindle Paperwhite for years now and love the fact
my eyes don’t get strained after reading for a few hours. It also lets me
read outside, under direct sunlight.
 This is more or less impossible with OLED displays. Sure, features like night
mode filter out blue light and can even turn the screen to monochrome,
but even when enabled OLED displays still don’t come close to matching e-
ink technology in terms of reading comfort.
 The smartphones of the future I envision would combine OLED and e-ink
technology into one, likely killing dedicated e-readers. With a simple tap in
the settings, you could transform an OLED display into an e-ink screen for
reading books, articles, and various documents without all that light
shining into your face.
 An e-ink display is also a lot less power hungry, which could mean longer
battery life.
11. Will there even be smartphones in the
future?

• Smartphones of the future may not be smartphones at all.


These devices may take on a whole new form factor, which
will enable us to perform the same tasks as smartphones do
today — and more.
• I see a future where smartphones in their current form get
replaced by what look like regular glasses. Yes, I know we’ve
already seen devices like Google Glass, which failed miserably.
But the product I have in mind goes beyond Google’s pet
project. It’s sort of like Google Glass on steroids.
Why android is different and
important?
• Choices: there is no monopoly of the particular
brand. we can purchase any phone from any
manufacturer unlike IOS or window.
• Cost efficient: competitions are within the
android phone developer, it reduces the cost.
• Flexibility: it is available from mobile version to
tabs, Android TV & Android auto.
• People choice: Android may be the most
successful mobile operating system in the world,
with an 80 per cent share of the global smart
phone market, but Google says it has little
influence on the devices people choose to buy.
Features of Android

There are many advantages of android. They are as follows:


• 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 Or Rich Site Summary) 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.
Categories of Android applications
There are many android applications in the market.
The top categories are:
• Entertainment
• Tools
• Communication
• Productivity
• Personalization
• Music and Audio
• Social
• Media and Video
• Travel and Local etc.
Android Stack(Architecture)
Android software stack (architecture) includes linux kernel, native
libraries (middleware), Android Runtime, Application Framework
and Applications.
Android Stack(Architecture) continued…….

Linux kernel
• is responsible for device drivers, power management & resource access
etc.
• Device drivers are: display driver, cam driver, keypad driver, wi-fi driver,
audio driver, flash memory driver etc.
• This is the Kernel on which android is based.
Native libraries
• On the top of linux kernel, there 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.
Android Stack(Architecture) continued…….

Android Run Time


• The android run time provides a set of core library that enable developers
to write android apps using java. The run time also includes the Dalvik
virtual machine, which enables every android apps to run in its own
process, with its own instance of Dalvik VM.
• Dalvik is a specialized VM designed specifically for android and optimized
for limited memory and CPU.
Application Framework
• Expose the various capabilities of android OS to application developers, so
that they can make use of them in their apps.
Applications
• At the top layer, we find application that ship with android apps such as
home, contacts, browser atc.
Android Applications Structure
Application components are the essential
building blocks of an android application structure.
Here are the five main application components:
• Activity
• Intent
• Service
• Content Provider
• Broadcast Receiver
1. Activity: An activity is a class that represents a single screen. It is like a Frame in AWT.
2. 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.
3. 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.
4. Content Provider:
• Content Providers are used to share data between the applications.
5. Broadcast Receiver : is a component that responds to system
wide broadcast announcement .many broadcast originate from the
system.
Ex- A broadcast announcing that battery is low, pictured captured etc.

Some others components are:


View
• A view is the UI element such as button, label, text field etc.
Anything that you see is a view.
Fragment
• Fragments are like parts of activity. An activity can display one or
more fragments on the screen at the same time.
AndroidManifest.xml
• It contains information about activities, content providers,
permissions etc. It is like the web.xml file in Java EE.
Project Structure of Android Application.
• File: MainActivity.java
package com.example.helloandroid;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.TextView;
public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
(1) 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.
(2) The onCreate method is called when Activity class is first created.
(3) The setContentView(R.layout.activity_main) gives information about our layout resource. Here, our layout
resources are defined in activity_main.xml file.
• File: activity_main.xml

<RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="@string/hello_world" />

</RelativeLayout>
As you can see, 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.
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.
*
* This class was automatically generated by the
* aapt tool from the resource data it found. It
* should not be modified by hand.
*/
package com.example.helloandroid;
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;
}

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.
Resources
• It contains resource files including activity_main,
strings, styles etc.
Manifest file
• It contains information about package including
components such as activities, services, content
providers etc.
Installing software for Android
following operating systems support android app development:
• Microsoft Windows XP or later version.
• Mac OS X 10.5.8 or later version with Intel chip.
• Linux including GNU C Library 2.7 or later.

Software Requirement:
• Java JDK5 or JDK6
• Android SDK
• Eclipse IDE for Java Developers (optional)
• Android Development Tools (ADT) Eclipse Plugin (optional)
Installing software for Android Contd.....

Step 1 - Setup Java Development Kit (JDK)


Set the path:
set PATH=C:\jdk1.6.0_15\bin;%PATH%
set JAVA_HOME=C:\jdk1.6.0_15

Step 2 - Setup Android SDK


We can download the latest version of Android SDK from Android
official website : develper.android.com/sdk
We will find a installer_rXX-windows.exe, so just download and run this
exe which will launch Android SDK Tool Setup wizard to guide
throughout of the installation
Installing software for Android Contd.....

• Next launch Android SDK Manager using the option:


All Programs > Android SDK Tools > SDK Manager,
this will give us the android sdk manager window to install required packages.

Click on install 7 packages -> accept license agreement and click on install.
SDK is installed.
Installing software for Android Contd.....

Step 3 - Setup Eclipse IDE


To install Eclipse IDE, download the latest Eclipse binaries from
http://www.eclipse.org/downloads/.
Step 4 - Setup Android Development Tools (ADT) Plugin
• This step will helps in setting Android Development Tool plugin for Eclipse.
Start Eclipse and then: Help > Software Updates > Install New Software.
• Now in the next window use Add button to add ADT Plugin as name and
https://dl-ssl.google.com/android/eclipse/ as the location.
• Then click OK to add this location
• and next button to complete the plugin installation
Installing software for Android Contd.....

Step 5 - Create Android Virtual Device


• To test android app in system we need AVD. Launch Android AVD Manager
using Eclipse menu options:
• Window > AVD Manager> which will launch Android AVD Manager.
• Use New button to create a new Android Virtual Device and enter the SDK
package number, CPU and memory information, before clicking on Create
AVD button.
Dalvik Virtual Machine

• As we know the modern JVM is high performance


and provides excellent memory management.
But it need to be optimized for low-powered
handheld devices.
• The Dalvik Virtual Machine (DVM) is optimized
for mobile devices. It optimizes the JVM
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 files that run on the Dalvik VM.
Dalvik Virtual Machine Contd…

The Android Assets Packaging Tool (aapt) handles the packaging process.
Application Context
• Context is an interface to global information about an application environment. It's
an abstract class whose implementation is provided by the Android system.
• Context allows access to application-specific resources and classes, as well as calls
for application-level operations such as launching activities, broadcasting and
receiving intents, etc.
Ex-
public class MyActivity extends Activity {
public void Testing()
{
Context actContext = this; /*returns the Activity Context since Activity extends Context.*/
Context appContext = getApplicationContext(); /*returns the context of the single, global Application object of
the current process. */
Button BtnShowAct1 = (Button) findViewById(R.id.btnGoToAct1);
Context BtnContext = BtnShowAct1.getContext(); /*returns the context of the View. */
}
}
To understand Context
• Another way to describe is, consider context as
remote of a TV & channel's in the television are
resources, services, using intents etc - - -
• Here remote acts as an access to get access to all
the different resources into foreground.
• So, Remote has access to channels such as
resources, services, using intents etc ....
• Likewise ..... Whoever has access to remote
naturally has access to all the things such as
resources, services, using intents etc
Activity Life Cycle
Activity Life Cycle
• We can control and manage the resource through the life
cycle methods of activity.
• There are 7 life cycle methods of android.app.Activity class.
They are as follows:
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.


Activity life cycle example
• Android Activity Life Cycle Example
• It provides the details about the invocation of life cycle methods of activity. In this example, we are displaying the content on the logcat.
File: MainActivity.java
package com.example.activitylifecycle;

import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d("lifecycle","onCreate invoked");
}
@Override
protected void onStart() {
super.onStart();
Log.d("lifecycle","onStart invoked");
}
@Override
protected void onResume() {

super.onResume();
Log.d("lifecycle","onResume invoked");
}
@Override
protected void onPause() {

super.onPause();
Log.d("lifecycle","onPause invoked");
}
@Override
protected void onStop() {

super.onStop();
Log.d("lifecycle","onStop invoked");
}

@Override
protected void onRestart() {

super.onRestart();
Log.d("lifecycle","onRestart invoked");
}
@Override
protected void onDestroy() {

super.onDestroy();
Log.d("lifecycle","onDestroy invoked");
}
}
Intents
Intent is the message that is passed between components
such as activities, content providers, broadcast receivers,
services etc.
The dictionary meaning of intent is intention or purpose. So,
it can be described as the intention to do action.

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.
Types of Intents
There are two types of intents in android: implicit and explicit.

1) 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.javatpoint.com"));
startActivity(intent);

2) Explicit Intent specifies the component. In such case, intent


provides the external class to be invoked.
Intent i = new Intent(getApplicationContext(), ActivityTwo.class);
startActivity(i);
Implicit Intent Example:
Activity class
File: MainActivity.java
package org.sssit.implicitintent;

import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends Activity {

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

final EditText editText1=(EditText)findViewById(R.id.editText1);


Button button1=(Button)findViewById(R.id.button1);

button1.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View arg0) {
String url=editText1.getText().toString();
Intent intent=new Intent(Intent.ACTION_VIEW,Uri.parse(url));
startActivity(intent);
}
});
}
}
Android Explicit Intent Example

Explicit intent specifies the component that is which class to be invoked.


We can pass the information from one activity to another using explicit intent.

Android app. calling one activity from another activity:


ActivityOne class ActivityTwo class
File: MainActivityOne.java File: MainActivityTwo.java
package com.example.explicitintent2; package com.example.explicitintent2;
import android.os.Bundle; import android.app.Activity;
import android.app.Activity; import android.content.Intent;
import android.content.Intent; import android.os.Bundle;
import android.view.View;
import android.view.Menu; import android.view.View.OnClickListener;
import android.view.View; import android.widget.Button;
import android.view.View.OnClickListener; import android.widget.EditText;
import android.widget.Button; import android.widget.TextView;
import android.widget.Toast; import android.widget.Toast;
public class ActivityTwo extends Activity {
public class ActivityOne extends Activity { @Override
public void onCreate(Bundle bundle) {
@Override super.onCreate(bundle);
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); TextView tv=new TextView(this);
setContentView(R.layout.activity_main); tv.setText("second activity");
setContentView(R.layout.activity_two);
Button button1=(Button)findViewById(R.id.Button01); Bundle extras = getIntent().getExtras();
button1.setOnClickListener(new OnClickListener(){ String value1 = extras.getString("Value1");
public void onClick(View view) { String value2 = extras.getString("Value2");
Intent i = new Intent(getApplicationContext(), ActivityTwo.class); Toast.makeText(getApplicationContext(),"Values are:\n F
i.putExtra("Value1", "Android By Javatpoint"); irst value: "+value1+
"\n Second Value: "+value2,Toast.LENGTH_LONG).show();
i.putExtra("Value2", "Simple Tutorial");
// Set the request code to any code you like, you can identify the Button button1=(Button)findViewById(R.id.Button01);
// callback via this code
startActivity(i); button1.setOnClickListener(new OnClickListener(){
public void onClick(View view) {
} Intent i = new Intent(getApplicationContext(), ActivityOn
}); e.class);
} startActivity(i);
} }
});
}
}
Toast
• A Toast is a transient message, meaning that it displays and disappears on its
own without user interaction. Moreover, it does not take focus away from the
currently active Activity, so if the user is busy writing the next Great
Programming Guide, keystrokes will not be “eaten” by the message.
• Since a Toast is transient, you have no way of knowing if the user even notices it.
You get no acknowledgment from the user, nor does the message stick around
for a long time to pester the user.
• Hence, the Toast is mostly for advisory messages, such as indicating a long-
running background task is completed, the battery has dropped to a low level,
and so on.
Syntax to create a toast:
Toast.makeText(getApplicationContext(), ”Message”, Toast.LENGTH_SHORT).show();
Alert
AlertDialog pops up, grabs the focus, and stays there until closed by the user.
You might use this for a critical error, like a validation message that cannot be effectively
displayed in the base activity UI, or some other situation where you are sure that the
user needs to see the message immediately.
How to create an alert in android app?

public void showAlert(View view) {


new AlertDialog.Builder(this)
.setTitle("MessageDemo")
.setMessage("Let's raise a toast!")
.setNeutralButton("Here, here!", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dlg, int sumthin) {
Toast.makeText(MessageDemo.this, "<clink, clink>", Toast.LENGTH_SHORT).show();
}
}).show();
}
Toggle Button
• Toggle Button can be used to display checked/unchecked (On/Off) state on the
button. It can be used to On/Off Sound, Wifi, Bluetooth etc.
• ToggleButton class provides the facility of creating the toggle button.
Constants of ToggleButton class:
• android:disabledAlpha The alpha to apply to the indicator when disabled.
• android:textOff The text for the button when it is not checked.
• android:textOn The text for the button when it is checked.
Methods of ToggleButton class:
• CharSequence getTextOff() Returns the text when the button is not in the
checked state.
• CharSequence getTextOn() Returns the text for when the button is in the
checked state.
• void setChecked(boolean checked) Changes the checked state of this
button.
package com.example.togglebutton;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
import android.widget.ToggleButton;

public class MainActivity extends Activity {


private ToggleButton toggleButton1, toggleButton2;
private Button buttonSubmit;

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

addListenerOnButtonClick();
}
public void addListenerOnButtonClick()
{ //Getting the ToggleButton and Button instance from the layout xml file
toggleButton1=(ToggleButton)findViewById(R.id.toggleButton1);
toggleButton2=(ToggleButton)findViewById(R.id.toggleButton2);
buttonSubmit=(Button)findViewById(R.id.button1);

//Performing action on button click


buttonSubmit.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View view) {
StringBuilder result = new StringBuilder();
result.append("ToggleButton1 : ").append(toggleButton1.getText());
result.append("\nToggleButton2 : ").append(toggleButton2.getText());
//Displaying the message in toast
Toast.makeText(getApplicationContext(), result.toString(),Toast.LENGTH_LONG).show();
}
});
}
}
Android UI Widgets
There are given a lot of UI widgets with simplified examples such as Button, EditText,
AutoCompleteTextView, ToggleButton, DatePicker, TimePicker, ProgressBar etc.
Button
Let's learn how to perform event handling on button click.
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
Let's see the application of simple food ordering.
AlertDialog
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
Let's see the simple example of 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.
Android CheckBox Example

Checkbox is a type of two state button either checked or unchecked.


There can be a lot of usage of checkboxes. For example, it can be
used to know the hobby of the user, activate/deactivate the specific
action etc.
CheckBox class
The android.widget.CheckBox class provides the facility of creating the
CheckBoxes.
Methods of CheckBox class
There are many inherited methods of View, TextView, Button etc.
classes in the CheckBox class. Some of them are as follows:
public boolean isChecked() Returns true if it is checked otherwise
false.
public void setChecked(boolean status) changes the state of the
CheckBox.???
import android.widget.*;

public class MainActivity extends Activity {


CheckBox pizza,coffee,burger;

Button buttonOrder;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addListenerOnButtonClick();
}
public void addListenerOnButtonClick(){
//Getting instance of CheckBoxes and Button from the activty_main.xml file
pizza=(CheckBox)findViewById(R.id.checkBox1);
coffee=(CheckBox)findViewById(R.id.checkBox2);
burger=(CheckBox)findViewById(R.id.checkBox3);
buttonOrder=(Button)findViewById(R.id.button1);
//Applying the Listener on the Button click
buttonOrder.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View view) {
int totalamount=0;
StringBuilder result=new StringBuilder();
result.append("Selected Items:");
if(pizza.isChecked()){
result.append("\nPizza 100Rs");
totalamount+=100;
}
if(coffe.isChecked()){
result.append("\nCoffe 50Rs");
totalamount+=50;
}
if(burger.isChecked()){
result.append("\nBurger 120Rs");
totalamount+=120;
}
result.append("\nTotal: "+totalamount+"Rs");
//Displaying the message on the toast
Toast.makeText(getApplicationContext(), result.toString(), Toast.LENGTH_LONG).show();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
Android Spinner Example
Spinner is like the combox box of AWT or Swing. It can be used to display the multiple
options to the user. Only one item can be selected by the user.
activity_main.xml
<RelativeLayout xmlns:androclass="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >

<Spinner
android:id="@+id/spinner1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="83dp" />

</RelativeLayout>
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements


AdapterView.OnItemSelectedListener {

String[] country = { "India", "USA", "China", "Japan", "Other", };

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Getting the instance of Spinner and applying OnItemSelectedListener on it
Spinner spin = (Spinner) findViewById(R.id.spinner1);
spin.setOnItemSelectedListener(this);

//Creating the ArrayAdapter instance having the country list


ArrayAdapter aa = new ArrayAdapter(this,android.R.layout.simple_spinner_item,country);
aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//Setting the ArrayAdapter data on the Spinner
spin.setAdapter(aa);
}
//Performing action onItemSelected and onNothing selected
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int position,long id) {
Toast.makeText(getApplicationContext(),country[position] ,Toast.LENGTH_LONG).s
how();
}

@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
Gallery & Image view
Gallery is a view that shows items (such as images)
in a center –locked, horizontal scrolling list.

Image view is to display image on the screen.


Steps:
1: keep images in the res/drawable folder in the
project.
2.Drag and drop gallery and image view on the app
and link the images to image views.
Android: Intent with parameters

To pass parameters from one activity to another is used the


method "intentobject.putExtra()“
//create an instance of the object
Object obj= new Object();
//creates an intent from the current activity to the destiny
activity with the data to be transferred.
Intent demo = new Intent(this,Second.class);
//transfers the object as a bundle to the next activity
demo.putExtra("OBJECT",obj);
startActivity(demo);
Getting Parameters from Intent

Bundle extras = getIntent().getExtras();

String value1 = extras.getString("Value1");


* Now the value1 can be used by text box, Toast, Text View or in any calculation.
Pending Intent
• A PendingIntent is a token that you give to a foreign application (e.g.
NotificationManager, AlarmManager, Home Screen AppWidgetManager, or
other 3rd party applications), which allows the foreign application to use your
application's permissions to execute a predefined piece of code.
• Pending means something is pending before intent execution.
• PendingIntent depends on Intent.
Ex- to create pending intent
Calendar cal = Calendar.getInstance();
Intent intent = new Intent(this, MyService.class);
PendingIntent pintent = PendingIntent.getService(this, 0, intent, 0);

AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);

alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 30*1000, pintent);


Diff…..
• If you give the foreign application an Intent, and that application
sends/broadcasts the Intent you gave, they will execute the Intent
with their own permissions.
• But if you instead give the foreign application a PendingIntent you
created using your own permission, that application will execute the
contained Intent using your application's permission.
• PendingIntent, Pending means something is pending before intent
execution. Or PendingIntent depend on Intent, Whereas Intent is not
pending anything or not depend on PendingIntent.

• Regular Intent -> DOES NOT REQUIRE PENDING INTENT TO BE MADE


• Pending Intent -> REQUIRES A REGULAR INTENT TO BE CREATED
Status bar Notification
• Status bar notifications indicates some ongoing
background services such as downloading or
playing music or displays an alert/information.
• To see the notification user needs to open the
notification drawer. Notifications are handled by
Notification Manger in Android.
• Notification Manager is a system service used to
manage notifications.
• We can create the status bar notification by using
two classes:
Notification & NotificationManager.
Ex-
• The NotificationManager is a system Service used to manage Notification. Get
a reference to it using the getSystemService() method.
• NotificationManager nm =
(NotificationManager)getSystemService(NOTIFICATION_SERVICE);
• Using the Notification Manager you can trigger new notifications, modify
existing ones, or cancel that are no longer required.
• Notification should contain - icon, text, Time Stamp, text - is the short
description of the alert such as 'New message', 'New email'
• Time Stamp- Time stamp is used to sort the notifications, NotificationManager
will sort the notifications.
• Notification notification = new Notification(R.drawable.ic_launcher, "New
Message", System.currentTimeMillis());
• Next, lets create a pending intent which will be invoked when the
message in status bar is clicked. Pending intents are intents and an
action to do so that it can passed to some other applications which
can execute this pendingintent.
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this,
0,notificationIntent, 0);

• I have passed the current activity to pendingIntent. The


pendingINtent specified will be fired of a user clicks notification
item.
• The simplest approach is to use the setLatestEventInfo() method to
specify the title and text fields.
notification.setLatestEventInfo(context, notificationTitle,
notificationMessage, pendingIntent)
• Finally post your notification to the status bar with a id. If a
notification with same id already exists, it will get replaced with
updated information.
nm.notify(9999, notification);
code
• NotificationManager nm = (NotificationManager)
getSystemService(NOTIFICATION_SERVICE);

• Notification nf = new Notification(R.drawable.ic_launcher,"New


Message", System.currentTimeMillis());

• Intent notificationIntent = new Intent(this, MainStatus.class);


• PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
notificationIntent, 0);

• nf.setLatestEventInfo(MainStatus.this, notificationTitle,
notificationMessage, pendingIntent);
• nm.notify(9999, nf);
Supporting multiple screen sizes
• Android runs on a variety of devices that offer different screen sizes and
densities. For applications, the Android system provides a consistent
development environment across devices and handles most of the work to
adjust each application's user interface to the screen on which it is
displayed.
• At the same time, the system provides APIs that allow us to control our
application's UI for specific screen sizes and densities, in order to optimize
our UI design for different screen configurations.
Terms:
• Screen size
• Density
• Orientation
Multiple Screen Size
Best Practices
• The objective of supporting multiple screens is to create an
application that can function properly and look good on any
of the generalized screen configurations supported by
Android.
Here is a quick checklist about how we can ensure that our
application displays properly on different screens:
• Use wrap_content, fill_parent, or dp units when specifying
dimensions in an XML layout file
• Do not use hard coded pixel values in your application code
• Do not use AbsoluteLayout (it's deprecated)
• Supply alternative bitmap drawables for different screen
densities
Unit-III(menus, medias)
Localization
(the process of translating a product into different languages or adapting a product for a
specific country or region)
• Android loads text and media resources from the project’s
‘res’ directory.
• For example, if the code loads a string called ‘R.string.title’,
Android will choose the correct value for that string at
runtime by loading the appropriate strings.xml file from a
matching ‘res/values’ directory.
• In order to have a multilingual Android app we need to
provide Android with the localized resource files.
If the locale is ‘en-US’, Android will look for a value of
“R.string.title” by searching the files in the following order:
1. ‘res/values-en-rUS/strings.xml’
2. ‘res/values-en/strings.xml’
3. ‘res/values/strings.xml’
• Table shows the paths to the different resource
files and which ones are used for which locale.

Location of “strings.xml” and background images for different locales


Localization Checklist

1. Never hard-code strings or string constants;


Instead use the R.string and strings.xml files.
2. Similarly, don’t hard-code images or layouts;
use R.drawable and R.layout
3. Translate the strings.xml files and localize
your images.
4. Place your localized resources in the
appropriate directories under ‘res/’.
Menu
There are different types of menus , such as:
1. Option menu
2. Context menu.
Android SDK provides the simple framework to add different
types of menus to the app.
1. 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, we need to
override onOptionsItemSelected() method of Activity class.
Creating Option Menu
Menu/Main_menu.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:context="com.example.menutst.MainMenu" >
<item android:id="@+id/item1"
android:title="option1"/>
<item android:id="@+id/item2"
android:title="option2"/>
<item android:id="@+id/item3"
android:title="option3"/>
</menu>
MainMenu.java

public class MainMenu extends Activity {

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

@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, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item)
{
int id = item.getItemId();
switch(id)
{
case R.id.item1: Toast.makeText(getApplicationContext(), "option1 is selected", Toast.LENGTH_LONG).show();
return true;
case R.id.item2:Toast.makeText(getApplicationContext(), "option 2 is selected", Toast.LENGTH_LONG).show();
return true;
case R.id.item3: Toast.makeText(getApplicationContext(), "option 3 is seleced", Toast.LENGTH_LONG).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
Context menu
• The context menu appears when user press long click on the
element. It is also known as floating menu.
• It doesn't support item shortcuts and icons.
onCreateContextMenu () method of Activity class is used to
create context method and
onContextItemSelected() method of Activity class is used to
implement action on selection of context menu.
Custom Dialog
• Custom dialog is an alert dialog with added button according to users requirement.
• It can have max 3 buttons.
Example-

AlertDialog.Builder builder = new AlertDialog.Builder(this);

builder.setMessage("Do you want to close this application ?")


.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Action for 'NO' Button
dialog.cancel();
}
})
.setNeutralButton("Dont Know", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//no action
}
}) ;
List View
• List views are the views that enable us to display a long list of items.
• In android there are two types of list views:
1. ListView
2. Spinner view
Both are useful to display long list of items.
1. ListView display a list of items in vertical scrolling list.
Ex-
ListView Lv;
String []items={“Kapil”,”Dhoni”,”Virat”,”Ashwin”};
Lv=(ListView)findViewById(R.id.listView1);
setListAdapter(new
ArrayAdapter<string>(this,android.R.layout.simpe_list_item_1,items));
Lv.setAdapter(adapter);
Spinner View
• SpinnerView displays one item at a time from a list and enables users to
choose among them.
• Generally its used when we don’t have much space on the screen to show
items list like ListView.
• Spinner is like the combox box of AWT or Swing. It can be used to display the
multiple options to the user. Only one item can be selected by the user.

Ex- <Spinner
android:id="@+id/spinner1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="83dp" />
Playing Audio, Video
• Android framework provides various APIs that allows us to add video,
audio, and photo capability to our application for playing and recording
media.
• We can play audio, video files in our application which are stored in raw
resource , file system, or from a data streaming incoming from network.

Android framework provides following class to play audio, video:


1. MediaPlayer: specifies the primary API for playing audio, video. This class
allows us to pay media from app resource, local file and from network.

2.AudioManager: manages audio source.


Using MediaPlayer
• In android, audio and video files and streams are managed by
Media players as a state machine.
The following transition take place in this state machine:
1. Initialize the media player with media to play.
2. Prepare the media player for playback.
3. Start the playback.
4. Use the pause or stop option for handling playback.
5. The playback is complete.
II Assignment
1. Differentiate between intent and pending intent
2. Write code for status bar notification.
3. Explain menus. Write the steps and code to create option
menu.
4. Write the steps and code to create a list of 10 students.
5. Write the codes to play audio from sdcard and net.
6. Define localization.
7. Write a program to play video from sdcard.
8. Write a note on SQLite.
9. Write a note on GPS and usage of GPS in mobile.
10. Write a note on google maps.
Playing Video using VideoView
• videoView is a control which can be used to view video on the
app. To support the videoView control on the app there is a class
called VideoView from widget package.
Ex- VideoView vv= (VideoView)findViewById(R.id.videoView1);
• MediaController is an inbuilt class from widget package, it helps to create
media control buttons(ex- forward, pause, back) on the player. It must be
used with videoView to have control on the video play.
Ex- mediaControls = new MediaController(MainVideo2.this);
vv.setMediaController(mediaControls);
vv.setVideoURI(Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.pvideo));
vv.start( );

• Video must be kept in the res/raw folder in the application.


Preparing Audio for playback
• To play audio, put audio file in res/raw folder
MediaPlayer mp=MediaPlayer.create(this, R.raw.audio1);
mp.start();
• To paly audio from network
MediaPlayer mp=MediaPlayer.create(this,
URI.parse(http://site.com/audio/a1.mp3));
mp.start();
• To play audio from sdcard.
MediaPlayer mp= new MediaPlayer();
mp.setDataSource(“/sdcard/myfavourite.mp3 ”);
mp.prepare();
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.MediaController;
import android.widget.VideoView;

public class MainVideo2 extends Activity


{
private VideoView vv;
private int position = 0;
private MediaController mc;

@Override
protected void onCreate(Bundle b) {
super.onCreate(b);
setContentView(R.layout.activity_main_video2);

//set the media controller buttons


if (mc == null) {
mc = new MediaController(this);
}
//initialize the VideoView
vv = (VideoView)findViewById(R.id.videoView1);
try {
//set the media controller in the VideoView
vv.setMediaController(mc);

//set the uri of the video to be played


vv.setVideoURI(Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.pvideo));

} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
vv.requestFocus();

//if we have a position on savedInstanceState, the video playback should start from here
vv.seekTo(position);
if (position == 0) {
vv.start();

} else {
//if we come from a resumed activity, video playback will be paused
vv.pause();
}

}
}
Data Storage Options
Android platform provides multiple mechanism for data
persistence. These mechanism depends on various factors,
such as the amount of data to be stored, frequency of data
accessibility, type of manipulation to be done on database etc.
Different data storage options or mechanism are:
1. The Preference
2. The Internal storage
3. The External storage
4. The SQLite database
5. The content provider
1. Preferences:
• Android provides many ways of storing data of an application. One of this
way is called Shared Preferences. Shared Preferences allow us to save and
retrieve data in the form of key, value pair.
• In order to use shared preferences, we have to call a method
getSharedPreferences() that returns a SharedPreference instance pointing
to the file that contains the values of preferences.
SharedPreferences sp= getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
Other modes:
• MODE_APPEND
• MODE_WORLD_READABLE
• MODE_WORLD_WRITEABLE
We can save something in the sharedpreferences by using SharedPreferences.Editor class. we will
call the edit method of SharedPreference instance and will receive it in an editor object. Its syntax
is −
Editor editor = sharedpreferences.edit();
editor.putString("key", "value");
editor.commit();
Other than putString( ), putLong( ), putFloat( ) etc methods can be used for long and float data.
SharedPreferences
• SharedPreferences is an API from Android SDK to
store and retrieve application preferences.
• SharedPreferences are simply sets of data values
that stored persistently. Persistently which mean
data you stored in the SharedPreferences are still
exist even if you stop the application or turn off
the device.
• SharedPreferences available at the Activity level
or shared across all Activity in application
package.
Example- To Write Preferences…………………………………………
public class MainActivity extends AppCompatActivity {
EditText ed1,ed2,ed3;
Button b1;

public static final String MyPREFERENCES = "MyPrefs" ;


public static final String Name = "nameKey";
public static final String Phone = "phoneKey";
public static final String Email = "emailKey";

SharedPreferences sp;

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

ed1=(EditText)findViewById(R.id.editText);
ed2=(EditText)findViewById(R.id.editText2);
ed3=(EditText)findViewById(R.id.editText3);
b1=(Button)findViewById(R.id.button);
sp= getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);

b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String n = ed1.getText().toString();
String ph = ed2.getText().toString();
String e = ed3.getText().toString();
SharedPreferences.Editor e= sp.edit();
e.putString(Name, n);
e.putString(Phone, ph);
e.putString(Email, e);
e.commit();
Toast.makeText(MainActivity.this,"Thanks",Toast.LENGTH_LONG).show();
}
});
}

}
Reading Preferences
public class ReadFref extends Activity
{
SharedPreferences sp;
String id,nm,cnt;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.readpref);

sp= getSharedPreferences("MyPREF", Context.MODE_PRIVATE);

id=sp.getString("ID",null);
nm=sp.getString("Name", null);
cnt=sp.getString("Contact",null);

Toast.makeText(this,"\nID"+id+"\nName"+nm+"\nContact"+cnt,Toast.LENGTH_LONG).show();
}
}
2. Internal Storage:
• You can save files directly on the device's internal storage. By
default, files saved to the internal storage are private to your
application and other applications cannot access them (nor can the
user). When the user uninstalls your application, these files are
removed.
To create and write a private file to the internal storage:
• Call openFileOutput() with the name of the file and the operating
mode. This returns a FileOutputStream.
• Write to the file with write().
• Close the stream with close().
For example:
String FILENAME = "hello_file";
String string = "hello world!";
FileOutputStream fos = openFileOutput(FILENAME,
Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();
• MODE_PRIVATE will create the file (or replace a
file of the same name) and make it private to
your application.
Other modes available are:
• MODE_APPEND,
• MODE_WORLD_READABLE, and
MODE_WORLD_WRITEABLE.
To read a file from internal storage:
• Call openFileInput() and pass it the name of the
file to read. This returns a FileInputStream.
• Read bytes from the file with read().
• Then close the stream with close().
public void read_file( )
{
try {
FileInputStream fis = context.openFileInput(filename);
InputStreamReader isr = new InputStreamReader(fis, "UTF-8");

BufferedReader bufferedReader = new BufferedReader(isr);


StringBuilder sb = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
sb.append(line).append("\n");
}
//print sb
} catch (FileNotFoundException e) { }

}
3. External Data storage:
Every Android-compatible device supports a shared
"external storage" that you can use to save files. This
can be a removable storage media (such as an SD card)
or an internal (non-removable) storage. Files saved to
the external storage are world-readable and can be
modified by the user when they enable USB mass
storage to transfer files on a computer.
• Caution: External storage can become unavailable if
the user mounts the external storage on a computer or
removes the media, and there's no security enforced
upon files you save to the external storage. All
applications can read and write files placed on the
external storage and the user can remove them.
• Getting access to external storage
• In order to read or write files on the external storage, your
app must acquire the READ_EXTERNAL_STORAGE or
WRITE_EXTERNAL_STORAGE system permissions. For
example:

• <manifest ...> <uses-permission


android:name="android.permission.WRITE_EXTERNAL_STO
RAGE" /> ... </manifest>

• If you need to both read and write files, then you need to
request only the WRITE_EXTERNAL_STORAGE permission,
because it implicitly requires read access as well.

• Note: Beginning with Android 4.4, these permissions are


not required if you're reading or writing only files that are
private to your app
Accessing SD Card
We can access the SD card from android using File
class and can read/write data to/from SD card
using FileOutputStream, FileInputStream classes.
//Ex of Writing data to SD card
File myFile = new File("/sdcard/mysdfile.txt");
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter = new
OutputStreamWriter(fOut);
myOutWriter.append(txtData.getText());

myOutWriter.close();
fOut.close();
//Ex of Reading data from SD card
File myFile = new File("/sdcard/mysdfile.txt");
FileInputStream fIn = new FileInputStream(myFile);
BufferedReader myReader = new BufferedReader(new
InputStreamReader(fIn));
String aDataRow = "";
String aBuffer = "";
while ((aDataRow = myReader.readLine()) != null) {
aBuffer += aDataRow + "\n";
}
txtData.setText(aBuffer);
saveButton.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
try {
FileOutputStream fos = new FileOutputStream(myExternalFile);
fos.write(inputText.getText().toString().getBytes());
fos.close();
} catch (IOException e) { e.printStackTrace(); }
inputText.setText("");
response.setText("SampleFile.txt saved to External Storage...");
}
});
readButton = (Button) findViewById(R.id.getExternalStorage);
readButton.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
try {
FileInputStream fis = new FileInputStream(myExternalFile);
DataInputStream in = new DataInputStream(fis);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null)
{
myData = myData + strLine;
}
in.close();
} catch (IOException e) { }
inputText.setText(myData);
response.setText("SampleFile.txt data retrieved from Internal Storage...");
}
});
if (!isExternalStorageAvailable() || isExternalStorageReadOnly())
{
saveButton.setEnabled(false);
}
else {
myExternalFile = new File(getExternalFilesDir(filepath), filename);
}
}
private static boolean isExternalStorageReadOnly()
{
String extStorageState = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(extStorageState)) {
return true;
} return false;
}
private static boolean isExternalStorageAvailable()
{
String extStorageState = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(extStorageState))
{
return true;
}
return false;
}
}
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
EditText textmsg;
static final int READ_BLOCK_SIZE = 100;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textmsg=(EditText)findViewById(R.id.editText1);
}
// write text to file
public void WriteBtn(View v) {
try {
FileOutputStream fileout=openFileOutput("mytextfile.txt", MODE_APPEND);
OutputStreamWriter outputWriter=new OutputStreamWriter(fileout);
outputWriter.write(textmsg.getText().toString());
outputWriter.close();
//display file saved message
Toast.makeText(getBaseContext(), "File saved successfully!“, Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
// Read text from file
public void ReadBtn(View v) {
try {
FileInputStream fileIn=openFileInput("mytextfile.txt");
InputStreamReader InputRead= new InputStreamReader(fileIn);
char[] inputBuffer= new char[READ_BLOCK_SIZE];
String s="";
int charRead;
while ((charRead=InputRead.read(inputBuffer))>0) {
// char to string conversion
String readstring=String.copyValueOf(inputBuffer,0,charRead);
s +=readstring;
}
InputRead.close();
Toast.makeText(getBaseContext(), s, Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
}
4. SQLite
• SQLite is a software library that implements a
self-contained, serverless, zero-configuration,
transactional SQL database engine.

• It is the most widely deployed SQL database


engine in the world. The source code for
SQLite is in the public domain.
Why SQLite?
• SQLite does not require a separate server process or system to
operate.(serverless).
• SQLite comes with zero-configuration, which means no setup or administration
needed.
• A complete SQLite database is stored in a single cross-platform disk file.
• SQLite is very small and light weight, less than 400KiB fully configured or less than
250KiB with optional features omitted.
• SQLite is self-contained, which means no external dependencies.
• SQLite transactions are fully ACID-compliant, allowing safe access from multiple
processes or threads. ClustrixDB,a NewSQL cloud database, comes with the added
benefit of guaranteed ACID(Automicity Consistency Isolation Durability)
transactions, critical for e-commerce success.
• SQLite supports most of the query language features found in the SQL92 (SQL2)
standard.
• SQLite is written in ANSI-C and provides simple and easy-to-use API.
• SQLite is available on UNIX (Linux, Mac OS-X, Android, iOS) and Windows (Win32,
WinCE, WinRT).
How to add SQLite Manager to your
browser
• Open Firefox Mozilla browser
• Click on Open Menu icon
• Click on Add_ons
• Search for SQLite Manager
• Click on AddToFirefox button
• SQLite Manager can be seen in the browser’s menu
Creating Database and Table in SQLite
Example- SQLite: creating database
public class DictionaryOpenHelper extends SQLiteOpenHelper {
private static final int DVersion= 2;
private static final String TNAME = "dictionary";
private static final String QRY =
"CREATE TABLE " + TNAME + " (" +
KEY_WORD + " TEXT, " +
KEY_DEFINITION + " TEXT);";
DictionaryOpenHelper(Context context) {
super(context, DATABASE_NAME, null, DVersion);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(QRY);
}
}
5. Content providers
• Content providers manage access to a structured set of data. They
encapsulate the data, and provide mechanisms for defining data security.
• Content providers are the standard interface that connects data in one
process with code running in another process.
• Android itself includes content providers that manage data such as audio,
video, images, and personal contact information .
SQLite Manager's interface
• Structure: In the rare situations where we add columns via point-and-click,
we can do it here.

• Browse & Search: In the relatively-rare situations (usually when we're


unfamiliar with the database) where we want to browse the data as if it
were a spreadsheet, this tab provides limited searching and editing
capability.

• Execute SQL: This is where we'll spend a majority of our time: writing SQL
queries, executing them, and seeing the filtered results.
SQLite Connectivity
• SQLite is a opensource SQL database that stores data to a text file
on a device. Android comes in with built in SQLite database
implementation.
• SQLite supports all the relational database features.
• In order to access this database, we don't need to establish any
kind of connections for it like JDBC,ODBC etc.
Database - Package
• The main package is android.database.sqlite that contains the
classes to manage our own databases.
Database - Creation
• In order to create a database we just need to call this method
openOrCreateDatabase with our database name and mode as a
parameter. It returns an instance of SQLite database which we have
to receive in our own object.
Syntax :
SQLiteDatabase mydatabase = openOrCreateDatabase("your database
name",MODE_PRIVATE,null);
Some other SQLite Function to open DB

Sr.No Method & Description

openDatabase(String path, SQLiteDatabase.CursorFactory factory, int flags, DatabaseErrorHandler errorHandler)


1 This method only opens the existing database with the appropriate flag mode. The common flags mode could be
OPEN_READWRITE OPEN_READONLY

openDatabase(String path, SQLiteDatabase.CursorFactory factory, int flags)


2 It is similar to the above method as it also opens the existing database but it does not define any handler to handle the errors of
databases

openOrCreateDatabase(String path, SQLiteDatabase.CursorFactory factory)


3
It not only opens but create the database if it not exists. This method is equivalent to openDatabase method

openOrCreateDatabase(File file, SQLiteDatabase.CursorFactory factory)


4
This method is similar to above method but it takes the File object as a path rather then a string. It is equivalent to file.getPath()
Operations On SQLite
1. Database - Insertion
we can create table or insert data into table using execSQL
method defined in SQLiteDatabase class.
Example:
SQLiteDatabase mydatabase = openOrCreateDatabase("your database name",MODE_PRIVATE,null);

mydatabase.execSQL("CREATE TABLE IF NOT EXISTS Login(Username VARCHAR,Password VARCHAR)");

mydatabase.execSQL("INSERT INTO Login VALUES('admin','admin')");


2. Database – Fetching
• We can retrieve anything from database using an object of the Cursor class.
We will call a method of this class called rawQuery and it will return a
resultset with the cursor pointing to the table. We can move the cursor
forward and retrieve the data.
• Cursor resultSet = mydatbase.rawQuery("Select * from Login",null);
• resultSet.moveToFirst();
• String username = resultSet.getString(0);
• String password = resultSet.getString(1);
How to Pull Database from SQLite
How to Pull Database from SQLite…….
• Click on the DDMS tab in Eclise IDE
• Click on the file explorer
• Explore the data/data/app_folder/database
• Select the database folder
• Click on Pull file from device icon
• Select a directory to save database in your
system.
To open the database:
• Open database from SQLite only by selecting
database folder in your system.
Database - Helper class
• For managing all the operations related to the database , a helper
class has been given and is called SQLiteOpenHelper.
• It automatically manages the creation and update of the database.
Syntax :
public class DBHelper extends SQLiteOpenHelper
{
public DBHelper(){
super(context,DATABASE_NAME,null,1);
}
public void onCreate(SQLiteDatabase db) { }
public void onUpgrade(SQLiteDatabase db, int oldd, int newd) { }
}
Example of -onCreate

@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(
"create table contacts " +
"(id integer primary key, name text, phone text, email text, street text,
place text)");
}
Example of -onUpgrage
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS contacts");
onCreate(db);
}
Database: deleting record
• Delete method from SQLiteDatabase is used to delete the
record from SQLite. It can be implemented in DatabaseHelper
class.
Ex- Delete function of DatabaseHelper class:
public Integer deleteRecord(Integer id)
{
SQLiteDatabase db = this.getWritableDatabase();
return db.delete(“Employee", "id = ? ", new String[] {
Integer.toString(id) });
}
Database: updating records
public boolean updateRecords (Integer id, String name, String phone, String email)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put("name", name);
cv.put("phone", phone);
cv.put("email", email);

db.update(“Employee", cv, "id = ? ", new String[] { Integer.toString(id) } );


return true;
}
Example of -Insert
public boolean insertContact (String name, String phone,
String email, String street,String place)
{

SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("name", name);
contentValues.put("phone", phone);
contentValues.put("email", email);
contentValues.put("street", street);
contentValues.put("place", place);
db.insert("contacts", null, contentValues);
return true;
}
Example of –getData & getRows
public Cursor getData(int id)
{
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from contacts where
id="+id+"", null );
return res;
}
…………………………………………………………………………………………………………
public int numberOfRows(){
SQLiteDatabase db = this.getReadableDatabase();
int numRows = (int) DatabaseUtils.queryNumEntries(db, tablename);
return numRows;
}
Example of -update
public boolean updateContact (Integer id, String name, String phone, String
email, String street,String place)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("name", name);
contentValues.put("phone", phone);
contentValues.put("email", email);
contentValues.put("street", street);
contentValues.put("place", place);
db.update("contacts", contentValues, "id = ? ", new String[] {
Integer.toString(id) } );
return true;
}
Example of -delete

public Integer deleteContact (Integer id)


{
SQLiteDatabase db = this.getWritableDatabase();
return db.delete("contacts", "id = ? ", new String[] { Integer.toString(id) });
}
Google Maps
• Google Maps is a desktop web mapping service developed by Google. It offers satellite
imagery, street maps, 360° panoramic views of streets (Street View), real-time traffic
conditions (Google Traffic), and route planning for traveling by foot, car, bicycle (in beta), or
public transportation.
• Google Maps began as a C++ desktop program designed by Lars and Jens Eilstrup Rasmussen
at Where 2 Technologies. In October 2004, the company was acquired by Google, which
converted it into a web application. After additional acquisitions of a geospatial data
visualization company and a realtime traffic analyzer, Google Maps was launched in February
2005. The service's front end utilizes JavaScript, XML, and Ajax.
• Google Maps offers an API that allows maps to be embedded on third-party websites,and
offers a locator for urban businesses and other organizations in numerous countries around
the world. Google Map Maker allows users to collaboratively expand and update the service's
mapping worldwide.
• Google Maps' satellite view is a "top-down" view; most of the high-resolution imagery of
cities is aerial photography taken from aircraft flying at 800 to 1,500 feet (240 to 460 m),
while most other imagery is from satellites. Much of the available satellite imagery is no
more than three years old and is updated on a regular basis. Google Maps uses a close
variant of the Mercator projection, and therefore cannot accurately show areas around the
poles.
Google Maps API

• Google launched the Google Maps API in June 2005 to allow


developers to integrate Google Maps into their websites. It is a free
service, and currently does not contain ads, but Google states in
their terms of use that they reserve the right to display ads in the
future.
• By using the Google Maps API, it is possible to embed Google Maps
site into an external website, on to which site specific data can be
overlaid. Although initially only a JavaScript API, the Maps API was
expanded to include an API for Adobe Flash applications (but this
has been deprecated), a service for retrieving static map images,
and web services for performing geocoding, generating driving
directions, and obtaining elevation profiles. Over 1,000,000 web
sites use the Google Maps API, making it the most heavily used web
application development API.
Embedding Google Map in the App
• Android allows us to integrate Google maps in our application.
• You can show any location on the map , or can show different routes on the map e.t.c.
• You can also customize the map according to your choices.
Google Map - Layout file
Now you have to add the map fragment into xml layout file. Its syntax is given below −
<fragment android:id="@+id/map"
android:name="com.google.android.gms.maps.MapFragment"
android:layout_width="match_parent" android:layout_height="match_parent"/>
Google Map - AndroidManifest file
• The next thing you need to do is to add some permissions along
with the Google Map API key in the AndroidManifest.XML file. Its
syntax is given below −
• <!--Permissions--> <uses-permission
android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission
android:name="com.google.android.providers.gsf.permission.
READ_GSERVICES" /> <uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE"
/>
• <!--Google MAP API key--> <meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="AIzaSyDKymeBXNeiFWY5jRUejv6zItpmr2MVyQ0" />
Customizing Google Map
• You can easily customize google map from its
default view , and change it according to your
demand.
• Adding Marker
• You can place a maker with some text over it
displaying your location on the map. It can be done
by via addMarker() method. Its syntax is given
below −
• final LatLng obj = new LatLng(21 , 57);
• Marker TP = googleMap.addMarker(new MarkerOptions()
.position(obj).title(“CMRIMS"));
Changing Map Type & Enabling Zoom
• You can also change the type of the MAP. There are four different
types of map and each give a different view of the map. These
types are Normal,Hybrid,Satellite and terrain. You can use them as
below
• googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
googleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
googleMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);

Enable/Disable zoom
• You can also enable or disable the zoom gestures in the map by
calling the setZoomControlsEnabled(boolean) method. Its syntax is
given below −
• googleMap.getUiSettings().setZoomGesturesEnabled(true);
import com.google.android.gms.maps.model.LatLng;
Code………….
import com.google.android.gms.maps.model.MarkerOptions;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback
{
private GoogleMap mMap;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
@Override
public void onMapReady(GoogleMap googleMap)
{
mMap = googleMap;
// Add a marker in Sydney and move the camera
LatLng LL = new LatLng(21, 57);
mMap.addMarker(new
MarkerOptions().position(LL).title(“CMR.EDU"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(LL));
}
}
The Global Positioning System (GPS)
• The Global Positioning System (GPS) is a satellite-based navigation system made up of a network of
24 satellites placed into orbit by the U.S. Department of Defense.
• GPS was originally intended for military applications, but in the 1980s, the government made the
system available for civilian use.
• GPS works in any weather conditions, anywhere in the world, 24 hours a day. There are no
subscription fees or setup charges to use GPS.
How it works
• GPS satellites circle the earth twice a day in a very precise orbit and transmit signal information to
earth.
• GPS receivers take this information and use trilateration to calculate the user's exact location.
Essentially, the GPS receiver compares the time a signal was transmitted by a satellite with the time
it was received. The time difference tells the GPS receiver how far away the satellite is. Now, with
distance measurements from a few more satellites, the receiver can determine the user's position
and display it on the unit's electronic map.
• A GPS receiver must be locked on to the signal of at least 3 satellites to calculate a 2-D position
(latitude and longitude) and track movement. With four or more satellites in view, the receiver can
determine the user's 3-D position (latitude, longitude and altitude). Once the user's position has
been determined, the GPS unit can calculate other information, such as speed, bearing, track, trip
distance, distance to destination, sunrise and sunset time and more.
• How accurate is GPS?
• Today's GPS receivers are extremely accurate.
GPS Implementation
• <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

• <uses-permission android:name="android.permission.INTERNET" />


public class GPSTracker extends Service implements LocationListener {
private final Context mContext;

// flag for GPS status


boolean isGPSEnabled = false;

// flag for network status


boolean isNetworkEnabled = false;

boolean canGetLocation = false;

Location location; // location


double latitude; // latitude
double longitude; // longitude
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10
meters

// The minimum time between updates in milliseconds


private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1
minute

// Declaring a Location Manager


protected LocationManager locationManager;

public GPSTracker(Context context) {


this.mContext = context;
getLocation();
}
Publishing an Application on Google Play
Part 1 - Preparing an Application for Release
After an application has been coded and tested, it is necessary to prepare a package
for distribution. The first task in preparing this package is to build the application
for release, which mainly entails setting some application attributes. Use the
following steps to build the app for release:
• Disable Debugging – This prevents users from trying to debug the application on a
device by using adb or other tools.
• Specify the Application Icon – Each Xamarin.Android application should have an
application icon specified. It is not technically required; however, some markets,
such as Google Play, require it.
• Version the Application – This step involves initializing or updating the versioning
information. This is important for future application updates and to ensure that
the users are aware of which version of the application they have installed.
• Configure the Linker – Linking is a step that is specific to Xamarin.Android and can
substantially reduce the size of the final APK by removing unused code.
• Set Packaging Properties – Packaging properties control the creation of the
Android application package (APK). This step optimizes the APK, protects its assets,
and modularizes the packaging as needed.
• Compile – This step compiles the code and assets to verify that it builds in Release
mode.
Part 2 - Signing the Android Application Package
After the application has been built for release, you sign the resulting APK
(Android application package) with a private key and zipalign it so that it is
ready for Android to run. This process is accomplished by using the
following steps:
• Create a Private Key – This step needs to be performed only once. A
private key is necessary to digitally sign the APK. After the private key has
been prepared, this step can be skipped for future release builds.
• Sign the APK – This step involves signing the APK with the private key that
was created in the previous step.
• Zipalign the APK – Zipalign is an optimization process that is performed on
an application. It enables Android to interact more efficiently with the APK
at runtime. Xamarin.Android conducts a check at runtime, and will not
allow the application to run if the APK has not been zipaligned.
• The last two steps of preparing an application for release differ in Xamarin
Studio and Visual Studio.
Publishing an Application on Google Play
• Although there are many app markets for distributing an application, Google Play is
arguable the largest and most visited store in the world for Android apps. Google Play
provides a single platform for distributing, advertising, selling, and analyzing the sales of
an Android application.
Requirement:
• one time fee of $25USD.
• All applications need to be signed with a cryptographic key that expires after October 22, 2033.
• The maximum size for an APK published on Google Play is 50MB

In order to publish applications on Google play it is necessary to have a publisher account.


To sign up for a publisher account follow these steps:
1. Visit the Google Play Android Developer console at
https://play.google.com/apps/publish .
2. Enter basic information about your developer identity.
3. Read and accept the Developer Distribution Agreement for your locale.
4. Pay the $25 USD registration fee.
5. Confirm verification by e-mail.
6. After the account has been created it is possible to publish applications using Google
Play.
Reference

You might also like