Android App Development - A Beginners Guide
Android App Development - A Beginners Guide
ANDROID TUTORIAL
CONTENTS
1.
2.
3.
4.
5.
6.
7.
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).
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.
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.
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.
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.
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
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.
<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>
3.
4.
5.
6.
7.
8.
9.
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
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
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;
sb1.setOnSeekBarChangeListener(new OnSeekBarChangeListener()
{
@Override
25
ViewFlipper:
Methods:
flipper.setFlipInterval(500);//setting the interval 500 milliseconds
flipper.startFlipping(); // starts flipping
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
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
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;
@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
Import:
import android.content.Intent;
Add the activity to the manifest:
<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" />
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);
Permissions:
<uses-permission android:name="android.permission.CAMERA"/>
<uses-feature android:name="android.hardware.camera"></uses-feature>
30
31
Bundle:
Dialogs:
1. Alert Dialog:
Import statements:
import android.app.AlertDialog;
import android.content.DialogInterface;
32
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()
34
WebView:
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:
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;
@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);
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
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()
<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;
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
android.app.Service;
android.content.Intent;
android.media.MediaPlayer;
android.os.IBinder;
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;
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>
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;
@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>
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
@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);
//alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()+
(time * 1000), pi);
50
MyBroadcastReceiver.java :
package com.example.alarm;
import
import
import
import
android.content.BroadcastReceiver;
android.content.Context;
android.content.Intent;
android.widget.Toast;
BroadcastReceiver
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>
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;
@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[]{"[email protected]"});
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
}
});
}
}
Screen Rotation:
</activity>
59