Sunteți pe pagina 1din 60

a

ANDROID TUTORIAL
CONTENTS
1.
2.
3.
4.
5.
6.
7.

Installing JDK and JRE


Installing Eclipse and Android SDK
Android Virtual Device Manager
Android SDK Manager
Creating a project
Folders
Layouts
Relative Layout
Grid Layout
List View
Scroll View
Table Layout
Linear Layout

8. Palette component
TextView
EditText
Button
ImageView
Image Button
Radio Button
CheckBox
Clocks
Spinner
Seekbar
Date/Time Picker
View Flipper
9. Toasts and Listeners
10. Intents

Activity
Call
Sms
Contact
Image Picker
1

Camera
View
Maps
Image from Gallery
Bundle

11. Dialogs
12. WebView
13. Media Player
14. Services
15. Broadcast Receivers
16. Menus
Context Menu
Options Menu
Pop up Menu
17. Wifi
18. Alarm
19. Sensor
20. Share option
21. Screen rotation
22. Volume control
23. Support different screen sizes
24. Upload APK to Google Play Store

Android is a mobile operating system (OS) based on the Linux kernel and currently
developed by Google. With a user interface based on direct manipulation, Android
is designed primarily for touchscreen mobile devices such as smartphones
and tablet computers, with specialized user interfaces for televisions (Android TV),
cars (Android Auto), and wrist watches (Android Wear).

1. Installing the JDK:


JDK is Java Development Kit and JRE is Java Runtime Environment.
Click on the link to download the latest version of the JDK
http://www.oracle.com/technetwork/java/javase/downloads/index.html

Accept the license agreement and choose the type of your operating system.
Download both JDK and JRE.
3

The JDK and JRE will be stored in the java folder in Program files otherwise create
a folder named java and copy the JDK and JRE and run the setup.

Set the jdk1.7 folder path in the Environment Variables:


Go to My Computer >Properties > Advanced System Setting > Environment
Variables > Path
Add a semicolon and copy the jdk1.7 folder path and paste it there.

For Eclipse with Android SDK:


Download Eclipse Indigo, Juno, Kepler or Luna
https://eclipse.org/downloads/packages/eclipse-ide-java-ee-developers/lunasr2
Choose the type of Operating System and agree to the terms and conditions.
2. To Install the ADT plugin:
3. Start Eclipse, then select Help > Install New Software.
4. Click Add, in the top-right corner.
5. In the Add Repository dialog that appears, enter "ADT Plugin" for the Name and the
following URL for the Location:
https://dl-ssl.google.com/android/eclipse/

Note: The Android Developer Tools update site requires a secure connection. Make sure the
update site URL you enter starts with HTTPS.
6. Click OK.
7. In the Available Software dialog, select the checkbox next to Developer Tools and
click Next.
8. In the next window, you'll see a list of the tools to be downloaded. Click Next.
9. Read and accept the license agreements, then click Finish.

If you get a security warning saying that the authenticity or validity of the software can't be
established, click OK.
10. When the installation completes, restart Eclipse.

Save both android sdk and eclipse in one folder and restart eclipse.

Setting up the Android SDK path:


Start Eclipse > Window > Preferences > Android > path
Give the path of your sdk folder in the path

Example: Androidsoftware is my folder which contains Eclipse and sdk, double click
on sdk and copy its path and paste it in the Eclipse Path.

Android Virtual Device Manager:


Start Eclipse > Window > Android Virtual Device Manager

Creating a new virtual device:


Enter the AVD name, choose the device and target and click on OK.

If your Virtual Device is taking too much time to start then perform
this action:
Go to the folder where you have saved the android sdk and eclipse.
Android sdk folder -> extras -> Intel ->Hardware_Accelerated_Execution_Manager
Run the intelhaxm setup in that folder.

Android SDK Manager:


You can install updates and packages here.
Start Eclipse > Window > Android SDK Manager
It is recommended to install all packages.

Creating the first project:


Start Eclipse - > file -> new -> Android Application Project
If you dont find Android Application Project there then go to Other -> Android
Application Project.
Click on Next -> Enter the Application Name -> Project Name -> Package name
Choose the Minimum Required SDK, Target SDK, Compile with and Theme.
Minimum Sdk is always given the smallest version depending on your app features
and compatibility. 2.0 (Froyo) for a simple app with just intents and other palette
components and 4.0(Ice cream sandwich) for apps with Action Bar, Grid Layout
etc.
If the apps version is low then many users will download the app as not many will
update the OS.
Launcher icon is the icon of your app which is visible when installed in a mobile.
10

1.The default launcher_icon is the android logo it is mandatory to change icon


either now or once your project is complete.
You can choose from your gallery or after creating the project go to
2. Res folder -> drawable hdpi ->drawable ldpi -> drawable mdpi -> copy paste the
picture which is your launcher icon into these folders and rename it as
launcher_icon and delete the android launcher icon.
You will know more about the res folder in the folders topic.
3. Choose the type of activity Blank, Full Screen or MasterFlow.
4. Give the Activity name and Layout name. Click on finish.
Activity is a java class and layout is an android xml file.

11

12

13

14

This has created the project TestingFirst with the java file and android xml file.
To run the project click on the green triangle icon at the top or right click on the
project and choose run as Android Application.

Folders:
Src Source folder which contains the activities (java files).
Gen Contains the R.java and BuildConfig files and it is automatically
generated.
Assests The key for the signed apk will be placed here.
Bin Contains the apk file
Libs Contains the libraries and any support library should be placed in this
folder.
Res This is the resource folder which contains images, audio & video, it
consists of 3 other folders drawable hdpi ldpi mdpi xxhdpi etc. These
folders contain the images to be used in the app.
Right click on res folder and choose create new folder and
name the folder as drawable in this folder paste the images
which you will use in your app.
Create a new folder and name is as raw folder and paste
audio or video inside it.
15

The layouts folder contains the android xml files.


The menu folder contains the menu items in case you use
menus in your app.
The values folder contains the strings.xml which contains the
app name and action settings which is used when you use an
action bar.

Android Manifest:

To declare applications(activities)
To add permissions
To add intent filters
To add portrait/landscape app screen orientation
To update apk
<application> </application> tag refers to the application
package and contains <activity></acitivity><intent-filters>
<category> etc.
<acitivity> represents the respective activity(the .java class)
Minsdkversion specifies the minimum sdk version for the app.

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


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.vibrate"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="8" />

<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.vibrate.MainActivity"
android:label="@string/app_name>
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

Naming Conventions for the res folder:


1. The images should be named in lowercase.
2. Only alphabets and digits are allowed.
16

3.
4.
5.
6.
7.
8.
9.

It should always start with an alphabet only.


The audio file should contain only alphabets.
It should be followed by .mp3 extension
Example: audii.mp3
White spaces and special characters not allowed.
The xml files should be named in alphabets and in lower case only.
Digits not allowed in the xml file.

Layouts:
It defines the visual structure of the UI.
1. Relative Layout :
Each element in positioned in relation with another element.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
</RelativeLayout>

2. Linear Layout :
Elements are displayed in a linear order.
It can be horizontal or vertical.
<LinearLayout
android:id="@+id/linearLayout1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView1"
android:layout_below="@+id/textView1"
android:orientation="horizontal" >

</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/linearLayout1"
android:layout_below="@+id/linearLayout1"
android:orientation="vertical" >

17

</LinearLayout>

Layout Width and Height can be set to Match Parent, Fill parent or wrap content.
3. Grid Layout :
Elements are displayed in a grid.
Required Android Version 4.0 and above.
4. Table Layout:
Elements are arranged in the form of rows and columns.
5. Scroll View:
Allows scrolling of the activity in your app.
It creates a default Linear Layout inside which you should add
the components to be scrolled.
6. ListView :
Elements are arranged in a list.
A custom listview is used to add image and text in a listview.

Class:
Class is defined as group of objects.
All the variable declarations can be done outside the class globally so that it is
accessible throughout the class.
The methods for the variable should be declared only inside the onCreate()
method.
It is created by default when an activity is created.
18

How to create a new class:


Right click on the package name
Click on new
Choose class
The class is created under the same package
Use extends keyword when you want to inherit classes
Add extends Activity when its an activity class
Add extends Service when its a service class
Add extends Broadcast Receiver when its a receiver class
You can also create multiple activities under the same package as it reduces the
task of creating a separate layout file.
The activity is added to the manifest directly but the class has to be declared in
the manifest manually.
Adding the Class to the Manifest:
Go to Android Manifest.mxl
Click on Application
Click on Add in Application Nodes column
Choose either Activity or Service etc.
It will browse for the name of the activity in the package
Choose the class and click on OK and perform Ctrl + s
The class will be added to the package
public class MainActivity extends Activity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);

// refers to the layout xml file


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

To add import statements: Ctrl + Shift + O

Palette Components:
All palette components have to be just dragged and dropped in the xml and declared in
the java file.
19

1.TextView :
Drag and drop a TextView in layout xml file.
Available in small, medium and large size.
Displays text.
Id: Represents the Id for the TextView (it can be changed )
Width and Height can be set to Match Parent, Fill Parent or Wrap Content.
Width and Height can also be given in numbers like 10dp, 50dp etc.
Margins are assigned as top 5dp, left 5dp right 5dp, bottom 6dp.
Color is set by the HTML color codes like #FFFFFF.
Text Size is given as numbers(18sp,20sp etc).
Typeface is text font.
Text Style can be Bold, Normal or Italic.

20

TextView declaration:
TextView textviewname;
Import statement:
import android.widget.TextView;
findViewById(int id) // Synatx to link id of the component to variable declared
textviewname=(TextView) findViewById(R.id.textView1);
textviewname.setText("Hello Android"); // most commonly used method
textviewname.setTextColor(Color.YELLOW);

Try out other methods by textviewname. (dot operator) will list out all the methods along
with description.

EditText:
Used as an edit box to get input from user.
Available under text fields of the palette component.
Import: import android.widget.EditText;
Declaration:
EditText et1; (EditText name)

et1=(EditText) findViewById(R.id.editText1);
String s=et1.getText().toString(); // to convert the input to String format

Try out other methods by using the dot operator.

Button:
Import
android.widget.Button;
Button b1;
b1=(Button) findViewById(R.id.button1);

ImageView:
It represents an image
The image has to be available in the drawable folder under the res folder
Width and height can be set to default parents or can be set as numbers
21

Import :android.widget.ImageView;
ImageView imageviewname; // syntax for declaration
imageviewname=(ImageView)findViewById(R.id.imageview1);
iv1.setImageResource( int resId); // syntax for setting the image
iv1.setImageResource(R.drawable.picc); // resID // drawable.imagename

ImageButton:
A regular button with image instead of text inside it.
22

Syntax:
ImageButton name;
Example : ImageButton ib;
Import : import android.widget.ImageButton;

Radio Button:
A round shaped button
Usually used for selecting/choosing purposes.
Syntax:
RadioButton name;
Example :
RadioButton rb1;
Import : android.widget.RadioButton;

CheckBox :
Synatx :
Checkbox name;
Example : Checkbox chb;
Import : android.widget.CheckBox;

Clocks :
Android has 2 types of clocks Analog and Digital
import android.widget.AnalogClock;
import android.widget.DigitalClock;
AnalogClock ac1; - Displays the analog clock
DigitalClock dc1; - Displays the digital clock
TimePicker and DatePicker
Allows choosing of Time and Date.
import android.widget.DatePicker;
import android.widget.TimePicker;
23

DatePicker dp;
TimePicker tp;

Spinner:
Provides an easy way to select from a set of values.
It displays a drop down menu.
Syntax:
Spinner sp1;
Declaration:
sp1=findViewById(R.id.spinner1);
Import:
android.widget.Spinner;
Populate the Spinner:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="subjects">
<item>English</item>
<item>Math</item>
<item>Science</item>
<item>Geography</item>
</string-array>
</resources>

Each item in the spinner is added in the strings.xml under res folder using <item> </item>.
Spinner sp1 = (Spinner) findViewById(R.id.spinner1);
// Create an ArrayAdapter using the string array and a default spinner
layout
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.subjects, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_it
em);
// Apply the adapter to the spinner
sp1.setAdapter(adapter);

The createFromResource() method allows you to create an ArrayAdapter from the string
array. The third argument for this method is a layout resource that defines how the selected
choice appears in the spinner control.
The simple_spinner_item layout is provided by the platform and is the default layout you
should use unless you'd like to define your own layout for the spinner's appearance.
24

You should then call setDropDownViewResource(int) to specify the layout the adapter
should use to display the list of spinner choices (simple_spinner_dropdown_item is another
standard layout defined by the platform).
Call setAdapter() to apply the adapter to your Spinner.
Seekbar:
It is a type of progress bar. It is usually used in Music Players.
Drag and drop a Seekbar from the palette.
Syntax: SeekBar seekbarname;
Example: Seekbar Sb1;
Declaration along with the id: sb1=(SeekBar) findViewById(R.id.seekBar1);
package com.example.firstproject;
import android.app.Activity;
import android.os.Bundle;
import android.widget.SeekBar; // Import Statement
import android.widget.SeekBar.OnSeekBarChangeListener;

public class MainActivity extends Activity


{
SeekBar sb1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sb1=(SeekBar) findViewById(R.id.seekBar1);

sb1.setOnSeekBarChangeListener(new OnSeekBarChangeListener()
{
@Override

25

public void onStopTrackingTouch(SeekBar arg0)


{ // to perform some task on stop of the Seekbar }
@Override
public void onStartTrackingTouch(SeekBar arg0)
{
// to perform some task on start of the seekbar
}
@Override
public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2)
{
// To perform some task on progress change of the seekbar
}
});
}
}

ViewFlipper:

Allows to flip between images


Syntax : ViewFlipper flipper;
Import: android.widget.ViewFlipper
Maximum of 4 images can be added

Methods:
flipper.setFlipInterval(500);//setting the interval 500 milliseconds
flipper.startFlipping(); // starts flipping

if(flipper.isFlipping())//Checking flipper is flipping or not.


{
flipper.stopFlipping(); //stops the flipping .
}
flipper.showNext();//shows the next view element of ViewFlipper

26

Toast:
A toast method is to display a message on the screen either for a short or long
period of time.
Syntax:
Toast.makeText(context, text, duration);
Toast t=Toast.makeText(getApplicationContext(), "Click on
image,Toast.LENGTH_LONG);
t.setGravity(Gravity.CENTER_HORIZONTAL, 170, 170);
t.show();
Toast.makeText(getApplicationContext(), "Click on the link",
Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(), "Click on the link", 1000).show(); //time
given in milliseconds
show() is the method to display the toast.

Listeners:
Used for handling android action events.

Event Handler

Event Listener & Description

onClick()

OnClickListener()
This is called when the user either clicks or touches or focuses upon any widget
like button, text, image etc. You will use onClick() event handler to handle such
event.

onLongClick()

OnLongClickListener()
This is called when the user either clicks or touches or focuses upon any widget
like button, text, image etc. for one or more seconds. You will use onLongClick()
event handler to handle such event.

onFocusChange()

OnFocusChangeListener()
This is called when the widget looses its focus ie. user goes away from the view
item. You will use onFocusChange() event handler to handle such event.

onKey()

OnFocusChangeListener()
This is called when the user is focused on the item and presses or releases a
hardware key on the device. You will use onKey() event handler to handle such
event.

onTouch()

OnTouchListener()
This is called when the user presses the key, releases the key, or any movement
gesture on the screen. You will use onTouch() event handler to handle such event.

onMenuItemClick()

OnMenuItemClickListener()
This is called when the user selects a menu item. You will use onMenuItemClick()

27

event handler to handle such event.

MainActivity.java class
import
import
import
import
import
import
import
import

android.app.Activity;
android.os.Bundle;
android.view.Menu;
android.view.View;
android.view.View.OnClickListener;
android.widget.Button;
android.widget.EditText;
android.widget.Toast;

public class MainActivity extends Activity


{
Button b1;
EditText et1,et2;

@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1=(Button) findViewById(R.id.button1);
et1=(EditText) findViewById(R.id.editText1);
et2=(EditText) findViewById(R.id.editText2);
// The OnClickListener method
b1.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View arg0)
{
Toast.makeText(getApplicationContext(), "Log in
successful", Toast.LENGTH_LONG).show();
}
});
} }
Refer the video for more details on how it is executed.

Intents:
Intent is used to pass message from one component to another or start another
activity or service.
Every Intent requires permissions to be added in the manifest.

28

Start another Activity:


To move from current activity to another activity.
Syntax and methods:
Intent intentname=new Intent(Currentclass.this,Otherclass.class);
Intentname.startActivity(); // to start an activity
Intentname.startService(); // to start a service
startActivityForResult(Intent, requestCode);

Import:
import android.content.Intent;
Add the activity to the manifest:

Click on the projects Android Manifest.xml


Double click on Application
Scroll down and in the application nodes column add the class
Click on Add Activity and browse the activitys name and save it(Ctrl + s)
The activity will be added to the manifest
In the same manner you can add your Receiver/ Service class

<activity android:name="com.proj.testingfirst.example">
</activity>

To make a call
Makes a call to the number given within the quotes directly.
Intent i = new Intent(Intent.ACTION_CALL,Uri.parse("tel:+91191828389"));
startActivity(i);
Give the mobile number inside Uri.parse().
<uses-permission android:name="android.permission.CALL_PHONE" />

To dial in the keypad


Opens the dial pad.
Intent i = new Intent(Intent.ACTION_DIAL,Uri.parse("tel:+9383389393"));
startActivity(i);

29

To send sms:
Intent i=new Intent(Intent.ACTION_SENDTO,Uri.parse("sms:+5556"));
i.putExtra("sms_body", "hi");
startActivity(i);
// putExtra() - adds the message hi to the sms body so hi will be sent to the number
5556.
<uses-permission android:name="android.permission.SEND_SMS" />

To pick a contact:
private static final int CONTACT_PICKER_RESULT = 1001;
Intent contactPickerIntent = new
Intent(Intent.ACTION_PICK,Contacts.CONTENT_URI);

//startActivityForResult(Intent, requestCode);
startActivityForResult(contactPickerIntent, CONTACT_PICKER_RESULT);

Check source code folder for full code.


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

To launch the camera:


static int CAMERA_PIC_REQUEST=1;
Intent i=new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
//startActivityForResult(Intent, requestCode);
startActivityForResult(i, CAMERA_PIC_REQUEST);
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_PIC_REQUEST)
{
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
iv1.setImageBitmap(thumbnail);
}

Permissions:
<uses-permission android:name="android.permission.CAMERA"/>
<uses-feature android:name="android.hardware.camera"></uses-feature>

To open the browser:


Intent t=new Intent(Intent.ACTION_VIEW,Uri.parse("http://www.google.com/"));
startActivity(t);

30

To open the Google Map:

//It takes the current location it can be blank.


String curr_address="";
//It takes the destination latitude and longitude.
String dest_address="12.822718,80.242019";
// Parse the current location and destination location to an Intent
Intent intent = new
Intent(android.content.Intent.ACTION_VIEW,Uri.parse("http://maps.google.c
om/maps?" + "saddr="+curr_address+ "&daddr="+dest_address ));
startActivity(intent);
To choose image from the android gallery:
ImageView iv2; // Declaring the ImageView where the selected image has to be
displayed.
iv2=(ImageView) findViewById(R.id.imageView2);
Intent i = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); // Intent
Declaration
startActivityForResult(i,1);

// the overriding method


@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if(resultCode==RESULT_OK) //choose image from gallery
{
Uri selectedImage = data.getData(); // get the selected image
String[] filePathColumn = { MediaStore.Images.Media.DATA }; // Store
it in a cursor
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
iv2.setImageBitmap(BitmapFactory.decodeFile(picturePath)); //display
the selected image in the ImageView
}
else if(resultCode==RESULT_CANCELED)
{
Toast.makeText(getApplicationContext(), "You haven't chosen an
image", Toast.LENGTH_LONG).show();
}
break;
}

31

Bundle:

Used for passing data between different activities.


It takes key and value as its parameter.
Passed using an intent
putExtra() is to parse the key and value to the bundle.
getExtra() is to get the value based on the key in another activity.
Bundle b=new Bundle();
b.putString(myname,anystring);
Intent intent=new Intent(getApplicationContext(),SecondActivity.class);
Intent.putExtra(mykey,anyvalue);
startActivity(intent);
Bundle extras=intent.getExtras();
String tmp=etras.getString(mykey);

Dialogs:
1. Alert Dialog:

Used to create alerts. Acts a like a pop up dialog.


Methods: alertdialogname.methodname();
setTitle(String) To set the title for the dialog
setMessage(String) To set the message for the dialog
setPositiveButton(Char sequence text, Onclicklistener listener); - for positive action
setNegativeButton(Char sequence text, Onclicklistener listener); - for negative action
setNeutalButton(Char sequence text, Onclicklistener listener); - for cancel action
create() To create the alert dialog
show() To show the alert dialog

Import statements:
import android.app.AlertDialog;
import android.content.DialogInterface;

Syntax: AlertDialog.Builder name=new AlertDialog.Builder(Classname.this);


AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this);

// Setting Dialog Title


alertDialog.setTitle("Action");
// Setting Dialog Message

32

alertDialog.setMessage("Confirm your action");


alertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
// Write your code here to execute after dialog closed
Toast.makeText(getApplicationContext(), "You clicked on Yes",
Toast.LENGTH_SHORT).show();
}
});

Progress Dialog:
Used to display the progress of an action like file download, loading of a webpage etc.
Import statement:
import android.app.ProgressDialog;
Declaration: Syntax : ProgressDialog name;
33

ProgressDialog progressDialog;
Methods: Progressdialogname.methodname()

.show(Context context, Title, Message) - to show the progress dialog


.setMessage(char sequence text) to set the message
.setTitle(char sequence text) to set the title
.setProgressStyle(progressdialogname.STYLE_HORIZONTAL) to display in horizontal
manner
.setProgressStyle(progressdialogname.STYLE_SPINNER) to display in a circular
manner
.dismiss() To close the progress dialog.
.setProgress(int value) to set a particular value
Syntax:
progressdialogname = ProgressDialog.show(classname.this, char sequence text, char
sequence text);
progressDialog = ProgressDialog.show(Progressact.this, "", "Loading...");

34

WebView:

Opens the webpage in the activity


Drag and drop the WebView component from the composite section of the palette.
Add internet permission in the Manifest.
<uses-permission android:name="android.permission.INTERNET"/>
Import statement : import android.webkit.WebView;
Declaration : WebView webviewname
Example: WebView w;

w=(WebView)findViewById(R.id.webView1);
String s="https://www.google.co.in/webhp?sourceid=chromeinstant&ion=1&espv=2&ie=UTF-8#q=Google";
w.loadUrl(s);
w.canScrollHorizontally(int direction);
w.canScrollVertically( int direction);
w.canZoomIn();
w.canZoomOut();

Media Player:

Used to play audio and video


Used either inside an activity or a service
Drag and drop the audio or video file inside the raw folder
The audio/video will be referenced using the file name in the raw folder.
Audio file should be of .mp3 format only.
Import statement: import android.media.MediaPlayer;
Declaration : MediaPlayer Mediaplayername
Example : MediaPlayer mp;
Methods: MediaPlayername.methodname(parameters)
.create(Context context int resid) to create the media player(Context can be this or
getApplicationContext().
mp=mp.create(this, R.raw.d) d is the name of the audio file
.start() - to start the mediaplayer
.play() to play the audio
.stop() to stop the audio
.pause() to pause the audio
.prepare() to prepare the audio to play
.release() to stop playing the audio
isPlaying() to check if audio is playing
isLooping() to check if the audio is in a loop
35

activity_main.xml: Contains two buttons inside a relative layout


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="48dp"
android:layout_marginTop="163dp"
android:text="Play" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/button1"
android:layout_toRightOf="@+id/button1"
android:text="Stop" />
</RelativeLayout>

MainActivity.java
package com.example.media;
import
import
import
import
import
import
import

android.app.Activity;
android.media.MediaPlayer;
android.os.Bundle;
android.view.View;
android.view.View.OnClickListener;
android.widget.Button;
android.widget.Toast;

public class MainActivity extends Activity


{
MediaPlayer mp; // declaration of the media player
Button b1,b2; // declaration of the button

@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1=(Button) findViewById(R.id.button1);
b2=(Button) findViewById(R.id.button2);

36

mp=mp.create(this, R.raw.d);

// d is the name of the audio file

b1.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View arg0)
{
mp.start(); // starts to play the song
Toast.makeText(getApplicationContext(), "Playing",
Toast.LENGTH_LONG).show();
}
});
b2.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View arg0)
{
mp.stop(); // stops the song
Toast.makeText(getApplicationContext(), "Stopped",
Toast.LENGTH_LONG).show();
}
});

Services:
A service is a component that runs in the background to perform long-running operations
without needing to interact with the user. For example, a service might play music in the
background while the user is in a different application, or it might fetch data over the
network without blocking user interaction with an activity.
Callback

Description

The system calls this method when another component, such


as an activity, requests that the service be started, by
onStartCommand() calling startService(). If you implement this method, it is your
responsibility to stop the service when its work is done, by
calling stopSelf() or stopService() methods.
onBind()

The system calls this method when another component wants


to bind with the service by calling bindService(). If you
37

implement this method, you must provide an interface that


clients use to communicate with the service, by returning
anIBinder object. You must always implement this method, but
if you don't want to allow binding, then you should return null.
onUnbind()

The system calls this method when all clients have


disconnected from a particular interface published by the
service.

onRebind()

The system calls this method when new clients have connected
to the service, after it had previously been notified that all had
disconnected in itsonUnbind(Intent).

onCreate()

The system calls this method when the service is first created
usingonStartCommand() or onBind(). This call is required to
perform one-time setup.

onDestroy()

The system calls this method when the service is no longer


used and is being destroyed. Your service should implement
this to clean up any resources such as threads, registered
listeners, receivers, etc.

MediaPlayer using Services:


When you want a song to be played as a background service or even when the app is
closed then you use the services concept where tasks work in the background.
The methods are same as in an activity.
You will use two classes an activity class and a service class.
Lukk.xml file:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
>

<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Play" />
<Button

38

android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="@+id/button1"
android:text="Stop" />
</RelativeLayout>

Lucky.java class:
package com.example.mymedia;
import
import
import
import
import
import
import

android.os.Bundle;
android.app.Activity;
android.content.Intent;
android.view.Menu;
android.view.View;
android.view.View.OnClickListener;
android.widget.Button;

public class Lucky extends Activity


{
Button b1,b2;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.luckk);
b1=(Button) findViewById(R.id.button1);
b2=(Button) findViewById(R.id.button2);
b1.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View arg0)
{
Intent i=new Intent(Lucky.this,luck.class);
startService(i); // intent to start the service
}
});

b2.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View arg0)
{
Intent i=new Intent(Lucky.this,luck.class);
stopService(i); // intent to stop the service
}
});

39

This is the service class:


package com.example.mymedia;
import
import
import
import

android.app.Service;
android.content.Intent;
android.media.MediaPlayer;
android.os.IBinder;

public class luck extends Service


{
MediaPlayer mp;
@Override
public IBinder onBind(Intent arg0)
{
return null;
}
public void onCreate()
{
mp=mp.create(this, R.raw.lucky); // create the mediaplayer inside
onCreate() method
}
public void onStart(Intent intent, int startid) // start the media player
inside onStart()
{
mp.start();
}
@Override
public void onDestroy() // stop the media player inside onStop()
{
mp.stop();
}
}

Broadcast Receivers:
Broadcast Receivers simply respond to broadcast messages from other applications or from
the system itself. These messages are sometime called events or intents. For example,
applications can also initiate broadcasts to let other applications know that some data has
been downloaded to the device and is available for them to use, so this is broadcast receiver
who will intercept this communication and will initiate appropriate action.

40

In order to implement Broadcast Receivers the class has to extend the Broadcast
Receiver class by using the keyword extends.
Eg: class MainActivity extends BroadcastReceiver
Import Statements: import android.content.BroadcastReceiver;
Mention the Broadcast Receiver class in the manifest.
The onReceive method:
public class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Intent Detected.",
Toast.LENGTH_LONG).show();
}
}

Options Menu:
This menu gives the user a set of options to choose from the menu hence the name
options menu.
We are inflating the menu inside the onCreateOptionsMenu(Menu menu) method
which is created by default in every activity.
Main.xml menu file can be found under the Menu folder inside the Res folder.
onOptionsItemSelected(Menuitem item) is the method which handles the event
when an option menu is selected.

<item> </item> is the tag to refer to the items inside the options menu. It is placed
inside the main.xml
MainActivity.java:
package com.example.optionsmenu;
import
import
import
import
import

android.app.Activity;
android.os.Bundle;
android.view.Menu;
android.view.MenuItem;
android.widget.Toast;

public class MainActivity extends Activity


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

41

@Override
public boolean onCreateOptionsMenu(Menu menu) // created by default
{
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) // to select the
options
{
switch (item.getItemId()) // use switch case to choose
{
case R.id.item1:
Toast.makeText(this, "Option1", Toast.LENGTH_SHORT).show();
return true;
case R.id.item2:
Toast.makeText(this, "Option2", Toast.LENGTH_SHORT).show();
return true;
case R.id.item3:
Toast.makeText(this, "Option3", Toast.LENGTH_SHORT).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}

Activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
</RelativeLayout>

Menu folder : main.xml


<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="@+id/action_settings"
android:orderInCategory="100"
android:showAsAction="never"

42

android:title="@string/action_settings"/>
<item android:id="@+id/item1" android:title="Option1"></item>
<item android:id="@+id/item2" android:title="Option2"></item>
<item android:id="@+id/item3" android:title="Option3"></item>
</menu>

android:id
A resource ID that's unique to the item, which allows the application can
recognize the item when the user selects it.
android:icon
A reference to a drawable to use as the item's icon.
android:title
A reference to a string to use as the item's title.
android:showAsAction
Specifies when and how this item should appear as an action item in
the action bar.

Context Menus:
This menu is used on long press.
import
import
import
import
import
import

android.app.Activity;
android.os.Bundle;
android.view.Menu;
android.view.MenuItem;
android.widget.Button;
android.widget.Toast;

import android.view.View;
import android.view.ContextMenu; //Import statements for the Context Menu
import android.view.ContextMenu.ContextMenuInfo;
public class MainActivity extends Activity
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btn = (Button) findViewById(R.id.btn1);
btn.setOnCreateContextMenuListener(this);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) // created by default
{
super.onCreateOptionsMenu(menu);
CreateMenu(menu);
return true;

43

}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
return MenuChoice(item);
}
@Override
public void onCreateContextMenu(ContextMenu menu, View view,
ContextMenuInfo menuInfo) // to create the context menu
{
super.onCreateContextMenu(menu, view, menuInfo);
CreateMenu(menu); // Calling the method CreateMenu
}
@Override
public boolean onContextItemSelected(MenuItem item)
{
return MenuChoice(item);
}
private void CreateMenu(Menu menu) // Method declaration
{
menu.setQwertyMode(true);
MenuItem mnu1 = menu.add(0, 0, 0, "1.technical"); // adding items to the
menu
{
}
MenuItem mnu2 = menu.add(0, 1, 1, "2.non tech");
{
}
MenuItem mnu3 = menu.add(0, 2, 2, "3.literary");
{
}
MenuItem mnu4 = menu.add(0, 3, 3, "4.Presentation");
{
}
}
private boolean MenuChoice(MenuItem item)
{
switch (item.getItemId()) {
case 0:
Toast.makeText(this, "You clicked on Technical",
Toast.LENGTH_LONG).show();
return true;
case 1:
Toast.makeText(this, "You clicked on Non tech",
Toast.LENGTH_LONG).show();
return true;
case 2:
Toast.makeText(this, "You clicked on Literary",
Toast.LENGTH_LONG).show();
return true;

44

case 3:
Toast.makeText(this, "You clicked on Presentation",
Toast.LENGTH_LONG).show();
return true;

}
return false;
}
}

Pop up Menus:
It displays the menu in pop up style or like a look up table.
MainActivity.java
package com.example.popup;
import android.app.Activity;
import android.content.Intent;
import
import
import
import
import
import
import
import

android.os.Bundle;
android.view.Menu;
android.view.MenuItem;
android.view.View;
android.view.View.OnClickListener;
android.widget.Button;
android.widget.PopupMenu;
// import statement
android.widget.PopupMenu.OnMenuItemClickListener;

public class MainActivity extends Activity implements OnClickListener,


OnMenuItemClickListener
{
Button b1;
PopupMenu pm;
private final static int ONE = 1;
private final static int TWO = 2;
private final static int THREE = 3;

@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1=(Button) findViewById(R.id.button1);
pm = new PopupMenu(this, b1); // creating the pop up menu
pm.getMenu().add(Menu.NONE, ONE, Menu.NONE, "1.Technical"); // adding
items to the menu
pm.getMenu().add(Menu.NONE, TWO, Menu.NONE, "2.Non Tech ");
pm.getMenu().add(Menu.NONE, THREE, Menu.NONE, "3.Presentation");
pm.setOnMenuItemClickListener(this);

45

b1.setOnClickListener(this);

}
@Override
public boolean onMenuItemClick(MenuItem item)
{
switch (item.getItemId())
{
case ONE:
Intent i=new Intent(MainActivity.this,Event1.class);
startActivity(i);
break;

case TWO:
Intent j=new Intent(MainActivity.this,Event2.class);
startActivity(j);
break;

case THREE:
Intent k=new Intent(MainActivity.this,Event3.class);
startActivity(k);
break;
}
return false;
}

@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
pm.show();
}
}

Event1.java:
package com.example.popup;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class Event1 extends Activity
{
TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_event1);
tv=(TextView) findViewById(R.id.textView1);

46

Main Menu
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="@+id/one"
android:title="One"/>
<item
android:id="@+id/two"
android:title="Two"/>
<item
android:id="@+id/three"
android:title="Three"/>
</menu>

Event1 menu
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="@+id/action_settings"
android:orderInCategory="100"
android:showAsAction="never"
android:title="@string/action_settings"/>
</menu>

Wifi:
To manage the wifi connectivity. It can be used to add network, disable network, scan for
access points, disconnect.
Syntax:
WifiManager wifiname = (WifiManager)getSystemService(Context.WIFI_SERVICE);

Example:
WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);

Methods:
wifiname.setWifienabled(true)
wifiname.setWifienabled(false)

MainAcitivity.java
package com.example.wifi;
import
import
import
import

android.app.Activity;
android.content.Context;
android.net.wifi.WifiManager;
android.os.Bundle;

47

import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity
{
Button enableButton,disableButton;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
enableButton=(Button)findViewById(R.id.button1);
disableButton=(Button)findViewById(R.id.button2);
enableButton.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
WifiManager wifi = (WifiManager)
getSystemService(Context.WIFI_SERVICE);
wifi.setWifiEnabled(true);
}
});
disableButton.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
WifiManager wifi = (WifiManager)
getSystemService(Context.WIFI_SERVICE);
wifi.setWifiEnabled(false);
}
});
}

Activity_main.xml :
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="76dp"
android:layout_marginTop="67dp"
android:text="Enable Wifi" />

48

<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/button1"
android:layout_below="@+id/button1"
android:layout_marginTop="44dp"
android:text="Disable Wifi" />
</RelativeLayout>

Add the following permissions in the manifest:


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

Alarm:
To create and set alarms
To create repeating alarms
Syntax:
AlarmManager alarmManagername = (AlarmManager) getSystemService(ALARM_SERVICE);

Example :
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);

Methods AlarmManagerName.methodname();
Syntax:
am.set(type, triggerAtMillis, operation)
Example:
am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()+ (time * 1000), pi);
Syntax for Repeating Alarm:
am.setRepeating(type, triggerAtMillis, intervalMillis, operation);

MainActivity.java :
package com.example.alarm;

import
import
import
import
import
import
import
import
import

android.app.Activity;
android.app.AlarmManager;
android.app.PendingIntent;
android.content.Intent;
android.os.Bundle;
android.view.View;
android.widget.Button;
android.widget.EditText;
android.widget.Toast;

49

public class MainActivity extends Activity {


Button b1;
EditText et1;

@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1=(Button) findViewById(R.id.button1);
}
public void startAlert(View view)
{
EditText text = (EditText) findViewById(R.id.editText1);

int time = Integer.parseInt(text.getText().toString());

Intent i = new Intent(this, MyBroadcastReceiver.class);

//PendingIntent pi = PendingIntent.getActivities(context, requestCode, intents,


flags)
PendingIntent pi = PendingIntent.getBroadcast(this.getApplicationContext(),
234324243, i, 0);

AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);

//alarmManager.set(type, triggerAtMillis, operation)

//alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()+
(time * 1000), pi);

//alarmManager.setRepeating(type, triggerAtMillis, intervalMillis,


operation);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
System.currentTimeMillis(),
1000 * 60 * 1, pi);
//AlarmManager.ELAPSED_REALTIME_WAKEUP
// AlarmManager.ELAPSED_REALTIME
Toast.makeText(this, "Alarm set in " + time + "
seconds",Toast.LENGTH_LONG).show();

50

MyBroadcastReceiver.java :
package com.example.alarm;
import
import
import
import

android.content.BroadcastReceiver;
android.content.Context;
android.content.Intent;
android.widget.Toast;

public class MyBroadcastReceiver extends


{

BroadcastReceiver

public void onReceive(Context context, Intent intent)


{
Toast.makeText(context, "time up!!!!.",Toast.LENGTH_LONG).show();
}

} Add the receiver class to the manifest

Activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="97dp"
android:layout_marginTop="34dp"
android:onClick="startAlert"
android:text="Setalarm" />
<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/button1"
android:layout_centerHorizontal="true"
android:layout_marginTop="38dp"
android:ems="10" />
</RelativeLayout>

51

Sensor Accelerometer:
Sensors can be used to monitor the three-dimensional device movement or change in the
environment of the device. There are three types of Sensors in Android
1. Motion Sensors to handle the motion along the x,y and z axis.
2. Positions Sensors
3. Environmental Sensors
Syntax:
SensorManager sensormanagername;

Example:
SensorManager sensorManager;
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
Setting the type of the Sensor as Accelerometer by using the below method:
sensorManager.registerListener(this, sensorManager.getDefaultSensor
(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL);

Other Methods:
Sensor.TYPE_GYROSCOPE;
Sensor.TYPE_LINEAR_ACCELERATION;
Sensor.TYPE_LIGHT;
Sensor.TYPE_PRESSURE;
Sensor.TYPE_MAGNETIC_FIELD;
Sensor.TYPE_TEMPERATURE;
Sensor.TYPE_ORIENTATION
Sensor.TYPE_RELATIVE_HUMIDITY

MainActivity.java class
package com.example.accelerometer;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.app.Activity;
import android.text.Html;
import android.widget.TextView;
public class MainActivity extends Activity implements SensorEventListener
{
SensorManager sensorManager;

//declaration

TextView x;
TextView y;

52

TextView z;
String sx, sy, sz;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Declaring 3 TextViews
x = (TextView) findViewById (R.id.textView2);
y = (TextView) findViewById (R.id.textView3);
z = (TextView) findViewById (R.id.textView4);
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
sensorManager.registerListener
(this, sensorManager.getDefaultSensor
(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL);
}

@Override
public void onAccuracyChanged(Sensor arg0, int arg1)
{
// TODO Auto-generated method stub
}
@Override
public void onSensorChanged(SensorEvent event)
{
// TODO Auto-generated method stub
if(event.sensor.getType() == Sensor.TYPE_ACCELEROMETER)
{
float xVal = event.values[0];
float yVal = event.values[1];
float zVal = event.values[2];
sx = "X value :"+ xVal ;
sy = "Y Value :"+ yVal;
sz = "Z Value :"+ zVal;
x.setText(Html.fromHtml(sx));
y.setText(Html.fromHtml(sy));
z.setText(Html.fromHtml(sz));
}
}
}

Activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/rl"
android:layout_width="match_parent"

53

android:layout_height="match_parent"
tools:context=".MainActivity" >
<TextView
android:id="@+id/textView1"
android:textSize="25sp"
android:textColor="#4169E1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="65dp"
android:text="Accelerometer" />
<TextView
android:id="@+id/textView2"
android:textSize="18sp"
android:textColor="#FF0000"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/textView3"
android:layout_centerHorizontal="true"
android:layout_marginBottom="30dp"
android:text="X Value" />
<TextView
android:id="@+id/textView3"
android:textSize="18sp"
android:textColor="#FF0000"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="Y Value" />
<TextView
android:id="@+id/textView4"
android:textSize="18sp"
android:textColor="#FF0000"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_below="@+id/textView3"
android:layout_marginTop="30dp"
android:text="Z Value" />
</RelativeLayout>

Share Via Email:


To share content via email
Syntax: Intent intentname = new Intent(Intent.ACTION_SEND);
Example: Intent sharingIntent = new Intent(Intent.ACTION_SEND);
Method to share through email:
54

sharingIntent.putExtra(Intent.EXTRA_EMAIL, new String[]{"recruit@yahoo.com"});


sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT,
Html.fromHtml("Name:"+et1.getText().toString()+"Phone number:"+et2.getText())); - to share the
text Name and phone number from 2 EditText boxes.
sharingIntent.setType("message/rfc822"); - setting the type of the message
Syntax: startActivity(Intent.createChooser(intentname,String msg));
Example: startActivity(Intent.createChooser(sharingIntent,"Share using"));

MainActivity.java class
package com.example.shareoption;
import
import
import
import
import
import
import
import

android.app.Activity;
android.content.Intent;
android.os.Bundle;
android.text.Html;
android.view.View;
android.view.View.OnClickListener;
android.widget.Button;
android.widget.EditText;

public class MainActivity extends Activity


{
Button b1;
EditText et1,et2;

@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et1=(EditText) findViewById(R.id.editText1);
et2=(EditText) findViewById(R.id.editText2);
b1=(Button) findViewById(R.id.button1);
b1.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View arg0)
{
Intent sharingIntent = new Intent(Intent.ACTION_SEND);
sharingIntent.putExtra(Intent.EXTRA_EMAIL, new
String[]{"recruit@yahoo.com"});
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT,
Html.fromHtml("Name:"+et1.getText().toString()+"\n"+"\n"+"Phone
number:"+et2.getText()));

55

sharingIntent.setType("message/rfc822");
startActivity(Intent.createChooser(sharingIntent,"Share using"));
}
});

Activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<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="23dp"
android:ems="10"
android:hint="Enter your name"
android:inputType="textPersonName" >
<requestFocus />
</EditText>
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/editText1"
android:layout_centerVertical="true"
android:layout_marginLeft="60dp"
android:text="Submit" />
<EditText
android:id="@+id/editText2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/editText1"
android:layout_below="@+id/editText1"
android:layout_marginTop="27dp"
android:ems="10"
android:hint="Enter Number"
android:inputType="phone" />

56

</RelativeLayout>

Sound Control:
Syntax:
AudioManager audiomanagername = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
Example:
AudioManager audiomanage = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
To set the ringer mode in either SILENT or NORMAL or VIBRATE mode:
audiomanage.setRingerMode(AudioManager.RINGER_MODE_SILENT);
audiomanage.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
audiomanage.setRingerMode(AudioManager.RINGER_MODE_NORMAL);

MainAcitivity.java
package com.example.vibrate;
import android.app.Activity;
import android.content.Context;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Vibrator;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity
{
Button b1;

@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1=(Button) findViewById(R.id.button1);
b1.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{

57

AudioManager audiomanage = (AudioManager)getSystemService(Context.AUDIO_SERVICE);


audiomanage.setRingerMode(AudioManager.RINGER_MODE_SILENT);
//audiomanage.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
//audiomanage.setRingerMode(AudioManager.RINGER_MODE_NORMAL);

}
});
}
}

Screen Rotation:

Two modes Portrait and Landscape


android:screenOrientation="landscape
android:screenOrientation="portrait"
Mention the required screen type in the Android Manifest.xml inside the respective
activity.
<activity
android:name="com.example.vibrate.MainActivity"
android:label="@string/app_name"
android:screenOrientation="landscape" >

</activity>

Support Different Screen Sizes:

Create three folders under the layouts folder


1. layout-normal for normal screen size
2. layout-large for large screen size
3. layout-xlarge for tablets
Drag and drop the respective layout.xml files inside these folders and adjust their
width, height and other alignments.

Steps to upload your app to the Google Play Store:


1. Create a Google Developer Account by paying an one time registration fee of 25$
using the Google Wallet.
2. Your apk has to be signed before it has to be uploaded.
3. Right click on your project -> Android Tools -> Export Signed Application Package ->
Create new keystore ->Give a password(Please remember the password) ->Give the
app name -> Destination of your app(usually the bin folder) -> place the key in the
assets folder -> Finish.
4. The key is very important if the key is changed or signature of apk is changed no
updates can be made for the apk in the Google PlayStore.
5. Select your apk from the bin folder of your project.
58

6. Upload the apk.


7. Upload a minimum of 2 screenshots of your app.
8. Give a brief description of your app.
9. Give the content rating for your app.
10. Agree to the terms and conditions.
11. Select the countries where you want your app to be published.
12. Choose publish application.
13. Your app will be available at the Play Store after a while.
References:
http://developer.android.com/guide/index.html
http://www.javatpoint.com/android-tutorial

59

S-ar putea să vă placă și