You are on page 1of 73

INDEX

Topic

SrNo.
1

Date

Page
2

Introduction

5
2

General Concepts

Android App Concepts

Activity

Manifest

6
7

13
27
39

Debugging In Eclipse

42

Android & BMI Calculator

45
8

Diagrammatic Overview
Using the Android Emulator

54

How to Use BMI Calculator

61

Limitations Future Enhancements

62

9
10

11

Sign

Introduction

Background:
Walky (as named) is an android based Research Project. It is an simple sleek application
compatible with most of the Android Phones running Operating System version2.3.6 or
above. Walky enables two Android based Phones to communicate each other with in
Local Area Network.
It Simulates Legacy Walky Talky(half duplex) but one which is IP based. This
research application is been optimized and incorporated with a Chat functionality along
with it.

Statement Of Problem:

Learn Android API


Make a Walky Talky Simulator for android user
Understanding Networking with Java.

Objective Of Thesis:
Aim was to learn an Android System to deep extent. Create a Deployable App using
Network and Other Hardware (mic & speakers). Also working with numerous Threads as
Android Applications are Thread Sensitive.

Basic but deep use of networking understanding behavior of network transfer.


Dealing with speech and different ways to send and receive voice message and
their optimization.
Extending Communication capability right from LAN (Local Area Network) to
WAN (Wide Area Network) or Internet.
Further Upgrading from Half Duplex to Full Duplex Communication like an IP
Phone (to Cheep IP phones).

Limitations:

Currently Walky is an amateur Research Based Project. It uses basic


network sockets to carry out its transfer operation.
For rest of the part there is intense use of Android API. And thats what it
is meant for.
It is not so stable and is buggy
Poorly carried out validation.
Needs some optimization.
Lack of knowledge of how actually Android OS(Operating System Works)
in detail.
Less use of System calls.
Android Version Compatibilities issue.(Is not Compatible with some low
end phones ).
Dependency on Access Points.(Only latest device have Wifi Direct
technology).
No Headset Button Support.
No Multicast Support.(One to many communication).
Still a BETA version.

Basic Requirements:
Android SDK.
Eclipse IDE (My Choice). +Android ADT plug in.
Java and XML knowledge.
Hardware Requirements:
Android Powered Phone
Min CPU 500MHz
SD card : min 10 Mb
Internal Memory : 3 MB when installed
Min Android API Version: 2.3 (Ginger Bread)
Max Android API Version: 4.0 (Ice Cream Sandwich)

General Concepts

What Is Android?
You might have seen windows, Linux and Mac operating systems which are made for
computers. Windows is the most popular operating system on computers. So if you know
about it then it is easy for you to get an answer for what is android.
Android is also an operating system developed by Google. Basically it was started by
some other company which was taken by Google. Google improved the operating system
and made it a open source platform. It was widely adapted over the world. As it is open
source it is so popular amongst the Smartphone. Android OS can also be used on tablet
PCs.

Official Android Logo.


Android is a Linux-based operating system designed primarily for touch screen mobile
devices.
Android is open source and Google releases the code under the Apache License.[11] This
open source code and permissive licensing allows the software to be freely modified and
distributed by device manufacturers, wireless carriers and enthusiast developers.
Additionally, Android has a large community of developers writing applications ("apps")
that extend the functionality of devices, written primarily in a customized version of
the Java programming language.

Android Versions:

Android beta.
1.5 Android Cupcake.
1.6 Android Donut.
2.0/2.1 clair.
2.2.x Froyo.
2.3.x Gingerbread.
3.x Honeycomb (used mainly for tablets.)
4.0.x Ice Cream Sandwich (both for phones and table)
4.1/4.2-JellyBeans.

As day by day there is a drastic development in hardware need for software support also
arise and later version are getting better and better with Multi-processor Devices.

Android Architecture:

Android consists of a kernel based on Linux kernel version 2.6 and, from Android 4.0 Ice
Cream Sandwich onwards, version 3.x, with middleware, libraries and APIs written in C,
and application software running on an application framework which includes Javacompatible libraries based on Apache Harmony. Android uses the Dalvik virtual
machine with just-in-time compilation to run Dalvik 'dex-code' (Dalvik Executable),
which is usually translated from Java byte code. The main hardware platform for Android
is the ARM architecture. There is support for x86 from the Android x86 project, and
Google uses a special x86 version of Android.
Android's Linux kernel has further architecture changes by Google outside the typical
Linux kernel development cycle. Android does not have a nativeX Window System by
default nor does it support the full set of standard GNU libraries, and this makes it
difficult to port existing Linux applications or libraries to Android. Support for simple C

and SDL applications is possible by injection of a small Java shim and usage of
the JNI like, for example, in the Jagged Alliance 2 port for Android.
Android App Concepts:

Android apps make life easier and are easy to understand. When people use your app for
the first time, they should intuitively grasp the most important features. The design work doesn't
stop at the first use, though. Android apps remove ongoing chores like file management and
syncing. Simple tasks never require complex procedures, and complex tasks are tailored to the
human hand and mind.
Design Principles

Android's system UI provides the framework on top of which you build your app.
important aspects include the Home screen experience, global device navigation, and
notifications.
Build visually compelling apps that look great on any device.
Use color and illumination to respond to touches, reinforce the resulting behaviors
of gestures, and indicate what actions are enabled and disabled.
Whenever a user touches an actionable area in your app, provide a visual
response. This lets the user know which object was touched and that your app is
"listening".
States

Most of Android's UI elements have touch-feedback built in, including states that
indicate whether touching the element will have any effect.

10

Patterns:
Design apps that behave in a consistent, predictable fashion.
UI (User Interface)
Android UI is an XML frame work and behavior is Java platform.
The graphical user interface for an Android app is built using a hierarchy
of View and View Group objects. View objects are usually UI widgets such
as buttons or text fields and View Group objects are invisible view containers that define
how the child views are laid out, such as in a grid or a vertical list.
Android provides an XML vocabulary that corresponds to the subclasses
of View and View Group so you can define your UI in XML using a hierarchy of UI
elements.

Ever thing is a view, a button is a view, a textview is a view or even a radio button is a
view.
Example of XML File
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="horizontal" >
</LinearLayout>

11

Layouts: Just like we use Flow Layout/ Border Layout in Java Swing applications, here
same goes for Linear Layout /Relative Layout to place any component or view in some
fashion.
LinearLayout
extends ViewGroup
A Layout that arranges its children in a single column or a single row. The direction of
the row can be set by calling setOrientation(). You can also specify gravity, which
specifies the alignment of all the child elements by calling setGravity() or specify that
specific children grow to fill up any remaining space in the layout by setting
the weight member of LinearLayout.LayoutParams. The default orientation is horizontal.

View
extends Object
implements Drawable.Callback KeyEvent.Callback AccessibilityEventSource
This class represents the basic building block for user interface components. A View
occupies a rectangular area on the screen and is responsible for drawing and event
handling. View is the base class for widgets, which are used to create interactive UI
components (buttons, text fields, etc.). The ViewGroupsubclass is the base class
for layouts, which are invisible containers that hold other Views (or other ViewGroups)
and define their layout properties.
For Example:
EditText
extends TextView
<EditText android:id="@+id/edit_message"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="@string/edit_message" />

12

INTERNATIONALISATION (I10Nationalization)
Android Application Strictly Follow I10Nationalization Concept.
Internationalization is the process by which one can make my web application to
use all languages. Main objectives are to develop a Web Application for Translation. I.e. to
add Multilingual Support to app.

Add String Resources


When you need to add text in the user interface, you should always specify each
string as a resource. String resources allow you to manage all UI text in a single location,
which makes it easier to find and update text. Externalizing the strings also allows you to
localize your app to different languages by providing alternative definitions for each
string resource.
By default, your Android project includes a string resource file
at res/values/strings.xml. Add a new string named "edit_message" and set the value to
"Enter a message." (You can delete the "hello_world" string.)
While youre in this file, also add a "Send" string for the button youll soon add,
called "button_send".
The result for strings.xml looks like this:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">My First App</string>
<string name="edit_message">Enter a message</string>
<string name="button_send">Send</string>
<string name="menu_settings">Settings</string>
<string name="title_activity_main">MainActivity</string>
</resources>

Then a button definition would look like this:


<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/button_send" />

13

Java Platform (Behavior)


While XML Scripts adds a Look and Feel to any Android APP, Java is responsible
to actual behavior and working of APP. When a user Press, Touch, Swipe any View on the
Screen a java code back there is responsible for carrying out the operations.
Activity and Service classes are the actual programmed component in all Android
participation.

14

Activity
extends ContextThemeWrapper
An activity is a single, focused thing that the user can do. Almost all activities interact
with the user, so the Activity class takes care of creating a window for you in which you
can place your UI withsetContentView(View). While activities are often presented to the
user as full-screen windows, they can also be used in other ways: as floating windows
(via a theme with windowIsFloating set) or embedded inside of another activity
(using ActivityGroup). There are two methods almost all subclasses of Activity will
implement:
onCreate(Bundle) is where you initialize your activity. Most importantly, here you
will usually callsetContentView(int) with a layout resource defining your UI, and
using findViewById(int) to retrieve the widgets in that UI that you need to
interact with programmatically.
onPause() is where you deal with the user leaving your activity. Most importantly,
any changes made by the user should at this point be committed (usually to
the ContentProvider holding the data).
To be of use with Context.startActivity(), all activity classes must have a
corresponding <activity>declaration in their package's AndroidManifest.xml.
Build an Intent
An Intent is an object that provides runtime binding between separate components (such
as two activities). The Intent represents an apps "intent to do something." You can use
intents for a wide variety of tasks, but most often theyre used to start another activity.

Intent intent = new Intent(this, DisplayMessageActivity.class);

An intent not only allows you to start another activity, but it can carry a bundle of data to
the activity as well. Inside thesendMessage() method, use findViewById() to get
theEditText element and add its text value to the intent:

15

public abstract class


Context
extends Object
Interface to global information about an application environment. This is an abstract class
whose implementation is provided by the Android system. It allows access to applicationspecific resources and classes, as well as up-calls for application-level operations such as
launching activities, broadcasting and receiving intents, etc
Starting an Activity
Unlike other programming paradigms in which apps are launched with a main() method,
the Android system initiates code in an Activity instance by invoking specific callback
methods that correspond to specific stages of its lifecycle. There is a sequence of callback
methods that start up an activity and a sequence of callback methods that tear down an
activity.

Activity Life Cycle


During the life of an activity, the system calls a core set of lifecycle methods in a
sequence similar to a step pyramid. That is, each stage of the activity lifecycle is a
separate step on the pyramid. As the system creates a new activity instance, each callback
method moves the activity state one step toward the top. The top of the pyramid is the
point at which the activity is running in the foreground and the user can interact with it.
16

Resumed
In this state, the activity is in the foreground and the user can interact with it. (Also
sometimes referred to as the "running" state.)
Paused
In this state, the activity is partially obscured by another activitythe other activity that's
in the foreground is semi-transparent or doesn't cover the entire screen. The paused
activity does not receive user input and cannot execute any code.
Stopped
In this state, the activity is completely hidden and not visible to the user; it is considered
to be in the background. While stopped, the activity instance and all its state information
such as member variables is retained, but it cannot execute any code.
The other states (Created and Started) are transient and the system quickly moves from
them to the next state by calling the next lifecycle callback method. That is, after the
system calls onCreate(), it quickly calls onStart(), which is quickly followed
by onResume().

The main activity for your app must be declared in the manifest with an <intentfilter> that includes the MAIN action and LAUNCHER category. For example:
<activity android:name=".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>

17

Activity Class Members (In Detail)

Activity
extends ContextThemeWrapper
implements ComponentCallbacks2 KeyEvent.Callback LayoutInflater.Factory2 View.OnCreateCo
ntextMenuListenerWindow.Callback
java.lang.Object
android.content.Context

android.content.ContextWrapper

android.view.ContextThemeWrapper

android.app.Activity
Known Direct Subclasses
AccountAuthenticatorActivity, ActivityGroup, AliasActivity, ExpandableListActivity, FragmentActivity,
ListActivity,NativeActivity
Known Indirect Subclasses
LauncherActivity, PreferenceActivity, TabActivity

Fragments
Starting with HONEYCOMB, Activity implementations can make use of
the Fragment class to better modularize their code, build more sophisticated user
interfaces for larger screens, and help scale their application between small and large
screens.
Activity Lifecycle
Activities in the system are managed as an activity stack. When a new activity is started,
it is placed on the top of the stack and becomes the running activity -- the previous
activity always remains below it in the stack, and will not come to the foreground again
until the new activity exits.
An activity has essentially four states:

18

If an activity in the foreground of the screen (at the top of the stack), it
is active or running.

If an activity has lost focus but is still visible (that is, a new non-full-sized or
transparent activity has focus on top of your activity), it is paused. A paused activity is
completely alive (it maintains all state and member information and remains attached
to the window manager), but can be killed by the system in extreme low memory
situations.

If an activity is completely obscured by another activity, it is stopped. It still


retains all state and member information, however, it is no longer visible to the user so
its window is hidden and it will often be killed by the system when memory is needed
elsewhere.

If an activity is paused or stopped, the system can drop the activity from memory
by either asking it to finish, or simply killing its process. When it is displayed again to
the user, it must be completely restarted and restored to its previous state.

The following diagram shows the important state paths of an Activity. The square
rectangles represent callback methods you can implement to perform operations when the
Activity moves between states. The colored ovals are major states the Activity can be in.

19

There are three key loops you may be interested in monitoring within your activity:

The entire lifetime of an activity happens between the first call


to onCreate(Bundle) through to a single final call to onDestroy(). An activity will do
all setup of "global" state in onCreate(), and release all remaining resources in
onDestroy(). For example, if it has a thread running in the background to download
data from the network, it may create that thread in onCreate() and then stop the thread
in onDestroy().

The visible lifetime of an activity happens between a call to onStart() until a


corresponding call toonStop(). During this time the user can see the activity on-screen,
though it may not be in the foreground and interacting with the user. Between these
two methods you can maintain resources that are needed to show the activity to the
user. For example, you can register a BroadcastReceiver in onStart() to monitor for
changes that impact your UI, and unregister it in onStop() when the user no longer
20

sees what you are displaying. The onStart() and onStop() methods can be called
multiple times, as the activity becomes visible and hidden to the user.

The foreground lifetime of an activity happens between a call


to onResume() until a corresponding call to onPause(). During this time the activity is
in front of all other activities and interacting with the user. An activity can frequently
go between the resumed and paused states -- for example when the device goes to
sleep, when an activity result is delivered, when a new intent is delivered -- so the code
in these methods should be fairly lightweight.

The entire lifecycle of an activity is defined by the following Activity methods. All of
these are hooks that you can override to do appropriate work when the activity changes
state. All activities will implementonCreate(Bundle) to do their initial setup; many will
also implement onPause() to commit changes to data and otherwise prepare to stop
interacting with the user. You should always call up to your superclass when
implementing these methods.
public class Activity extends ApplicationContext {
protected void onCreate(Bundle savedInstanceState);
protected void onStart();
protected void onRestart();
protected void onResume();
protected void onPause();
protected void onStop();
protected void onDestroy();
}

21

Configuration Changes
If the configuration of the device (as defined by the Resources.Configuration class)
changes, then anything displaying a user interface will need to update to match that
configuration. Because Activity is the primary mechanism for interacting with the user, it
includes special support for handling configuration changes.
Unless you specify otherwise, a configuration change (such as a change in screen
orientation, language, input devices, etc) will cause your current activity to be destroyed,
going through the normal activity lifecycle process of onPause(), onStop(),
and onDestroy() as appropriate. If the activity had been in the foreground or visible to the
user, once onDestroy() is called in that instance then a new instance of the activity will be
created, with whatever savedInstanceState the previous instance had generated
fromonSaveInstanceState(Bundle).
This is done because any application resource, including layout files, can change based
on any configuration value. Thus the only safe way to handle a configuration change is to
re-retrieve all resources, including layouts, drawables, and strings. Because activities
must already know how to save their state and re-create themselves from that state, this is
a convenient way to have an activity restart itself with a new configuration.
In some special cases, you may want to bypass restarting of your activity based on one or
more types of configuration changes. This is done with
the android:configChanges attribute in its manifest. For any types of configuration
changes you say that you handle there, you will receive a call to your current
activity's onConfigurationChanged(Configuration) method instead of being restarted. If a
configuration change involves any that you do not handle, however, the activity will still
be restarted andonConfigurationChanged(Configuration) will not be called.
Starting Activities and Getting Results
The startActivity(Intent) method is used to start a new activity, which will be placed at
the top of the activity stack. It takes a single argument, an Intent, which describes the
activity to be executed.
Sometimes you want to get a result back from an activity when it ends. For example, you
may start an activity that lets the user pick a person in a list of contacts; when it ends, it
returns the person that was selected. To do this, you call the startActivityForResult(Intent,
int) version with a second integer parameter identifying the call. The result will come
back through your onActivityResult(int, int, Intent) method.
When an activity exits, it can call setResult(int) to return data back to its parent. It must
always supply a result code, which can be the standard results RESULT_CANCELED,
RESULT_OK, or any custom values starting at RESULT_FIRST_USER. In addition, it
22

can optionally return back an Intent containing any additional data it wants. All of this
information appears back on the parent'sActivity.onActivityResult(), along with the
integer identifier it originally supplied.
If a child activity fails for any reason (such as crashing), the parent activity will receive a
result with the code RESULT_CANCELED.
public class MyActivity extends Activity {
...
static final int PICK_CONTACT_REQUEST = 0;
protected boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
// When the user center presses, let them pick a contact.
startActivityForResult(
new Intent(Intent.ACTION_PICK,
new Uri("content://contacts")),
PICK_CONTACT_REQUEST);
return true;
}
return false;
}

protected void onActivityResult(int requestCode, int resultCode,


Intent data) {
if (requestCode == PICK_CONTACT_REQUEST) {
if (resultCode == RESULT_OK) {
// A contact was picked. Here we will just display it
// to the user.
startActivity(new Intent(Intent.ACTION_VIEW, data));
}
}
}

23

Process Lifecycle

The Android system attempts to keep application process around for as long as possible,
but eventually will need to remove old processes when memory runs low. As described
in Activity Lifecycle, the decision about which process to remove is intimately tied to the
state of the user's interaction with it. In general, there are four states a process can be in
based on the activities running in it, listed here in order of importance. The system will
kill less important processes (the last ones) before it resorts to killing more important
processes (the first ones).
1.

The foreground activity (the activity at the top of the screen that the user is
currently interacting with) is considered the most important. Its process will only be
killed as a last resort, if it uses more memory than is available on the device. Generally
at this point the device has reached a memory paging state, so this is required in order
to keep the user interface responsive.

2.

A visible activity (an activity that is visible to the user but not in the foreground,
such as one sitting behind a foreground dialog) is considered extremely important and
will not be killed unless that is required to keep the foreground activity running.

3.

A background activity (an activity that is not visible to the user and has been
paused) is no longer critical, so the system may safely kill its process to reclaim
memory for other foreground or visible processes. If its process needs to be killed,
when the user navigates back to the activity (making it visible on the screen again),
its onCreate(Bundle) method will be called with the savedInstanceState it had
previously supplied in onSaveInstanceState(Bundle) so that it can restart itself in the
same state as the user last left it.

4.

An empty process is one hosting no activities or other application components


(such as Service orBroadcastReceiver classes). These are killed very quickly by the
system as memory becomes low. For this reason, any background operation you do
outside of an activity must be executed in the context of an activity BroadcastReceiver
or Service to ensure that the system knows it needs to keep your process around.

Sometimes an Activity may need to do a long-running operation that exists independently


of the activity lifecycle itself. An example may be a camera application that allows you to
upload a picture to a web site. The upload may take a long time, and the application
should allow the user to leave the application will it is executing. To accomplish this,
your Activity should start a Service in which the upload takes place. This allows the
system to properly prioritize your process (considering it to be more important than other
non-visible applications) for the duration of the upload, independent of whether the
original activity is paused, stopped, or finished.

24

[Expand]

Inherited Constants
From class android.content.Context
From interface android.content.ComponentCallbacks2
Public Constructors
Activity()

Public Methods
void

addContentView(View view, ViewGroup.LayoutParams params)


Add an additional content view to the activity.

void

closeContextMenu()
Programmatically closes the most recently opened context menu, if showing.

void

closeOptionsMenu()
Progammatically closes the options menu.

PendingIntent

createPendingResult(int requestCode, Intent data, int flags)


Create a new PendingIntent object which you can hand to others for them to use to send
result data back to your onActivityResult(int, int, Intent)callback.

final void

dismissDialog(int id)
This method was deprecated in API level 13. Use the new DialogFragment class
with FragmentManager instead; this is also available on older platforms through the
Android compatibility package.

boolean

dispatchGenericMotionEvent(MotionEvent ev)
Called to process generic motion events.

boolean

dispatchKeyEvent(KeyEvent event)
Called to process key events.

boolean

dispatchKeyShortcutEvent(KeyEvent event)
Called to process a key shortcut event.

boolean

dispatchPopulateAccessibilityEvent(AccessibilityEvent event)
Called to process population of AccessibilityEvents.

boolean

dispatchTouchEvent(MotionEvent ev)
Called to process touch screen events.

boolean

dispatchTrackballEvent(MotionEvent ev)
Called to process trackball events.

void

dump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args)


Print the Activity's state into the given stream.

View

findViewById(int id)
Finds a view that was identified by the id attribute from the XML that was processed
in onCreate(Bundle).

void

finish()
Call this when your activity is done and should be closed.

void

finishActivity(int requestCode)
Force finish another activity that you had previously started
with startActivityForResult(Intent, int).

25

void

finishActivityFromChild(Activity child, int requestCode)


This is called when a child activity of this one calls its finishActivity().

void

finishAffinity()
Finish this activity as well as all activities immediately below it in the current task that
have the same affinity.

void

finishFromChild(Activity child)
This is called when a child activity of this one calls its finish() method.

ActionBar

getActionBar()
Retrieve a reference to this activity's ActionBar.

final Applicatio
n

getApplication()
Return the application that owns this activity.

ComponentNam
e

getCallingActivity()
Return the name of the activity that invoked this activity.

String

getCallingPackage()
Return the name of the package that invoked this activity.

int

getChangingConfigurations()
If this activity is being destroyed because it can not handle a configuration parameter
being changed (and thus itsonConfigurationChanged(Configuration) method
is not being called), then you can use this method to discover the set of changes that
have occurred while in the process of being destroyed.

ComponentNam
e

getComponentName()
Returns complete component name of this activity.

View

getCurrentFocus()
Calls getCurrentFocus() on the Window of this Activity to return the currently focused
view.

FragmentManag
er

getFragmentManager()
Return the FragmentManager for interacting with fragments associated with this
activity.

Intent

getIntent()
Return the intent that started this activity.

Object

getLastNonConfigurationInstance()
This method was deprecated in API level 13. Use the
new Fragment API setRetainInstance(boolean) instead; this is also available on older
platforms through the Android compatibility package.

LayoutInflater

getLayoutInflater()
Convenience for calling getLayoutInflater().

LoaderManager

getLoaderManager()
Return the LoaderManager for this fragment, creating it if needed.

String

getLocalClassName()
Returns class name for this activity with the package prefix removed.

MenuInflater

getMenuInflater()
Returns a MenuInflater with this context.

final Activity

getParent()
Return the parent activity if this view is an embedded child.

Intent

getParentActivityIntent()
Obtain an Intent that will launch an explicit target activity specified by this activity's
logical parent.

SharedPreferenc
es

getPreferences(int mode)
Retrieve a SharedPreferences object for accessing preferences that are private to this

26

activity.
void

onBackPressed()
Called when the activity has detected the user's press of the back key.

void

onConfigurationChanged(Configuration newConfig)
Called by the system when the device configuration changes while your activity is
running.

void

onContentChanged()
This hook is called whenever the content view of the screen changes (due to a call
to Window.setContentView or Window.addContentView).

boolean

onContextItemSelected(MenuItem item)
This hook is called whenever an item in a context menu is selected.

void

onContextMenuClosed(Menu menu)
This hook is called whenever the context menu is being closed (either by the user
canceling the menu with the back/menu button, or when an item is selected).

void

onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo m


enuInfo)
Called when a context menu for the view is about to be shown.

CharSequence

onCreateDescription()
Generate a new description for this activity.

void

onCreateNavigateUpTaskStack(TaskStackBuilder builder)
Define the synthetic task stack that will be generated during Up navigation from a
different task.

boolean

onCreateOptionsMenu(Menu menu)
Initialize the contents of the Activity's standard options menu.

boolean

onCreatePanelMenu(int featureId, Menu menu)


Default implementation of onCreatePanelMenu(int, Menu) for activities.

View

onCreatePanelView(int featureId)
Default implementation of onCreatePanelView(int) for activities.

boolean

onCreateThumbnail(Bitmap outBitmap, Canvas canvas)


Generate a new thumbnail for this activity.

View

onCreateView(View parent, String name, Context context, AttributeSet attrs)


Standard implementation of onCreateView(View, String, Context, AttributeSet) used
when inflating with the LayoutInflater returned bygetSystemService(String).

View

onCreateView(String name, Context context, AttributeSet attrs)


Standard implementation of onCreateView(String, Context, AttributeSet) used when
inflating with the LayoutInflater returned bygetSystemService(String).

void

onDetachedFromWindow()
Called when the main window associated with the activity has been detached from the
window manager.

boolean

onGenericMotionEvent(MotionEvent event)
Called when a generic motion event was not handled by any of the views inside of the
activity.

boolean

onKeyDown(int keyCode, KeyEvent event)


Called when a key was pressed down and not handled by any of the views inside of the
activity.

boolean

onKeyLongPress(int keyCode, KeyEvent event)


Default implementation of KeyEvent.Callback.onKeyLongPress(): always returns false
(doesn't handle the event).

boolean

onKeyMultiple(int keyCode, int repeatCount, KeyEvent event)

27

Default implementation of KeyEvent.Callback.onKeyMultiple(): always returns false


(doesn't handle the event).
boolean

onKeyShortcut(int keyCode, KeyEvent event)


Called when a key shortcut event is not handled by any of the views in the Activity.

boolean

onKeyUp(int keyCode, KeyEvent event)


Called when a key was released and not handled by any of the views inside of the
activity.

void

onLowMemory()
This is called when the overall system is running low on memory, and would like
actively running process to try to tighten their belt.

boolean

onMenuItemSelected(int featureId, MenuItem item)


Default implementation of onMenuItemSelected(int, MenuItem) for activities.

boolean

onMenuOpened(int featureId, Menu menu)


Called when a panel's menu is opened by the user.

boolean

onNavigateUp()
This method is called whenever the user chooses to navigate Up within your
application's activity hierarchy from the action bar.

boolean

onNavigateUpFromChild(Activity child)
This is called when a child activity of this one attempts to navigate up.

boolean

onOptionsItemSelected(MenuItem item)
This hook is called whenever an item in your options menu is selected.

void

onOptionsMenuClosed(Menu menu)
This hook is called whenever the options menu is being closed (either by the user
canceling the menu with the back/menu button, or when an item is selected).

void

onPanelClosed(int featureId, Menu menu)


Default implementation of onPanelClosed(int, Menu) for activities.

void

onPrepareNavigateUpTaskStack(TaskStackBuilder builder)
Prepare the synthetic task stack that will be generated during Up navigation from a
different task.

boolean

onPrepareOptionsMenu(Menu menu)
Prepare the Screen's standard options menu to be displayed.

boolean

onPreparePanel(int featureId, View view, Menu menu)


Default implementation of onPreparePanel(int, View, Menu) for activities.

Object

onRetainNonConfigurationInstance()
This method was deprecated in API level 13. Use the
new Fragment API setRetainInstance(boolean) instead; this is also available on older
platforms through the Android compatibility package.

boolean

onSearchRequested()
This hook is called when the user signals the desire to start a search.

boolean

onTouchEvent(MotionEvent event)
Called when a touch screen event was not handled by any of the views under it.

boolean

onTrackballEvent(MotionEvent event)
Called when the trackball was moved and not handled by any of the views inside of the
activity.

void

onTrimMemory(int level)
Called when the operating system has determined that it is a good time for a process to
trim unneeded memory from its process.

void

onUserInteraction()
Called whenever a key, touch, or trackball event is dispatched to the activity.

28

void

onWindowAttributesChanged(WindowManager.LayoutParams params)
This is called whenever the current window attributes change.

void

onWindowFocusChanged(boolean hasFocus)
Called when the current Window of the activity gains or loses focus.

ActionMode

onWindowStartingActionMode(ActionMode.Callback callback)
Give the Activity a chance to control the UI for an action mode requested by the system.

void

openOptionsMenu()
Programmatically opens the options menu.

void

overridePendingTransition(int enterAnim, int exitAnim)


Call immediately after one of the flavors of startActivity(Intent) or finish() to specify an
explicit transition animation to perform next.

void

recreate()
Cause this Activity to be recreated with a new instance.

void

registerForContextMenu(View view)
Registers a context menu to be shown for the given view (multiple views can show the
context menu).

final void

removeDialog(int id)
This method was deprecated in API level 13. Use the new DialogFragment class
with FragmentManager instead; this is also available on older platforms through the
Android compatibility package.

final boolean

requestWindowFeature(int featureId)
Enable extended window features.

final void

runOnUiThread(Runnable action)
Runs the specified action on the UI thread.

void

setContentView(int layoutResID)
Set the activity content from a layout resource.

void

setContentView(View view)
Set the activity content to an explicit view.

void

setContentView(View view, ViewGroup.LayoutParams params)


Set the activity content to an explicit view.

final void

setDefaultKeyMode(int mode)
Select the default key handling for this activity.

final void

setFeatureDrawable(int featureId, Drawable drawable)


Convenience for calling setFeatureDrawable(int, Drawable).

final void

setFeatureDrawableAlpha(int featureId, int alpha)


Convenience for calling setFeatureDrawableAlpha(int, int).

final void

setFeatureDrawableResource(int featureId, int resId)


Convenience for calling setFeatureDrawableResource(int, int).

final void

setFeatureDrawableUri(int featureId, Uri uri)


Convenience for calling setFeatureDrawableUri(int, Uri).

void

setFinishOnTouchOutside(boolean finish)
Sets whether this activity is finished when touched outside its window's bounds.

void

setIntent(Intent newIntent)
Change the intent returned by getIntent().

final void

setProgress(int progress)
Sets the progress for the progress bars in the title.

final void

setProgressBarIndeterminate(boolean indeterminate)

29

Sets whether the horizontal progress bar in the title should be indeterminate (the circular
is always indeterminate).
final void

setProgressBarIndeterminateVisibility(boolean visible)
Sets the visibility of the indeterminate progress bar in the title.

final void

setProgressBarVisibility(boolean visible)
Sets the visibility of the progress bar in the title.

void

setRequestedOrientation(int requestedOrientation)
Change the desired orientation of this activity.

Manifest

AndroidManifest.xml
Every application must have an AndroidManifest.xml file (with precisely that name) in
its root directory. The manifest presents essential information about the application to the
Android system, information the system must have before it can run any of the
application's code. Among other things, the manifest does the following:

It names the Java package for the application. The package name serves as a
unique identifier for the application.

It describes the components of the application the activities, services,


broadcast receivers, and content providers that the application is composed of. It
names the classes that implement each of the components and publishes their
capabilities (for example, which Intent messages they can handle). These declarations
let the Android system know what the components are and under what conditions they
can be launched.

It determines which processes will host application components.

It declares which permissions the application must have in order to access


protected parts of the API and interact with other applications.

It also declares the permissions that others are required to have in order to interact
with the application's components.

It lists the Instrumentation classes that provide profiling and other information as
the application is running. These declarations are present in the manifest only while
the application is being developed and tested; they're removed before the application is
published.

It declares the minimum level of the Android API that the application requires.

It lists the libraries that the application must be linked against

30

Structure of the Manifest File


The diagram below shows the general structure of the manifest file and every element
that it can contain. Each element, along with all of its attributes, is documented in full in a
separate file. To view detailed information about any element, click on the element name
in the diagram, in the alphabetical list of elements that follows the diagram, or on any
other mention of the element name.

31

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


<manifest>
<uses-permission />
<permission />
<permission-tree />
<permission-group />
<instrumentation />
<uses-sdk />
<uses-configuration />
<uses-feature />
<supports-screens />
<compatible-screens />
<supports-gl-texture />
<application>
<activity>
<intent-filter>
<action />
<category />
<data />
</intent-filter>
<meta-data />
</activity>
<activity-alias>
<intent-filter> . . . </intent-filter>
<meta-data />
</activity-alias>
<service>
<intent-filter> . . . </intent-filter>
<meta-data/>
</service>
<receiver>
<intent-filter> . . . </intent-filter>
<meta-data />
</receiver>
<provider>
<grant-uri-permission />
<meta-data />
<path-permission />
</provider>
<uses-library />
</application>
</manifest>

32

All the elements that can appear in the manifest file are listed below in alphabetical
order. These are the only legal elements; you cannot add your own elements or
attributes.
<action>
<activity>
<activity-alias>
<application>
<category>
<data>
<grant-uri-permission>
<instrumentation>
<intent-filter>
<manifest>
<meta-data>
<permission>
<permission-group>
<permission-tree>
<provider>
<receiver>
<service>
<supports-screens>
<uses-configuration>
<uses-feature>
<uses-library>
<uses-permission>
<uses-sdk>

File Features
The following sections describe how some Android features are reflected in the manifest
file.
Intent Filters
The core components of an application (its activities, services, and broadcast receivers)
are activated byintents. An intent is a bundle of information (an Intent object) describing
a desired action including the data to be acted upon, the category of component that
should perform the action, and other pertinent instructions. Android locates an
appropriate component to respond to the intent, launches a new instance of the
component if one is needed, and passes it the Intent object.
Components advertise their capabilities the kinds of intents they can respond to
through intent filters. Since the Android system must learn which intents a component
33

can handle before it launches the component, intent filters are specified in the manifest
as <intent-filter> elements. A component may have any number of filters, each one
describing a different capability.
An intent that explicitly names a target component will activate that component; the filter
doesn't play a role. But an intent that doesn't specify a target by name can activate a
component only if it can pass through one of the component's filters.
For information on how Intent objects are tested against intent filters, see a separate
document, Intents and Intent Filters.
Icons and Labels
A number of elements have icon and label attributes for a small icon and a text label that
can be displayed to users. Some also have a description attribute for longer explanatory
text that can also be shown on-screen. For example, the <permission> element has all
three of these attributes, so that when the user is asked whether to grant the permission to
an application that has requested it, an icon representing the permission, the name of the
permission, and a description of what it entails can all be presented to the user.
In every case, the icon and label set in a containing element become the
default icon and label settings for all of the container's subelements. Thus, the icon and
label set in the <application> element are the default icon and label for each of the
application's components. Similarly, the icon and label set for a component for
example, an <activity> element are the default settings for each of the
component's<intent-filter> elements. If an <application> element sets a label, but an
activity and its intent filter do not, the application label is treated as the label for both the
activity and the intent filter.
The icon and label set for an intent filter are used to represent a component whenever the
component is presented to the user as fulfilling the function advertised by the filter. For
example, a filter with "android.intent.action.MAIN" and
"android.intent.category.LAUNCHER" settings advertises an activity as one that initiates
an application that is, as one that should be displayed in the application launcher. The
icon and label set in the filter are therefore the ones displayed in the launcher.
Permissions
A permission is a restriction limiting access to a part of the code or to data on the device.
The limitation is imposed to protect critical data and code that could be misused to distort
or damage the user experience.
Each permission is identified by a unique label. Often the label indicates the action that's
restricted. For example, here are some permissions defined by Android:

34

android.permission.CALL_EMERGENCY_NUMBERS
android.permission.READ_OWNER_DATA
android.permission.SET_WALLPAPER
android.permission.DEVICE_POWER
A feature can be protected by at most one permission.
If an application needs access to a feature protected by a permission, it must declare that
it requires that permission with a <uses-permission> element in the manifest. Then, when
the application is installed on the device, the installer determines whether or not to grant
the requested permission by checking the authorities that signed the application's
certificates and, in some cases, asking the user. If the permission is granted, the
application is able to use the protected features. If not, its attempts to access those
features will simply fail without any notification to the user.
An application can also protect its own components (activities, services, broadcast
receivers, and content providers) with permissions. It can employ any of the permissions
defined by Android (listed inandroid.Manifest.permission) or declared by other
applications. Or it can define its own. A new permission is declared with
the <permission> element. For example, an activity could be protected as follows:
<manifest . . . >
<permission android:name="com.example.project.DEBIT_ACCT" . . . />
<uses-permission android:name="com.example.project.DEBIT_ACCT" />
...
<application . . .>
<activity android:name="com.example.project.FreneticActivity"
android:permission="com.example.project.DEBIT_ACCT"
...>
...
</activity>
</application>
</manifest>
Note that, in this example, the DEBIT_ACCT permission is not only declared with
the <permission> element, its use is also requested with the <uses-permission> element.
Its use must be requested in order for other components of the application to launch the
protected activity, even though the protection is imposed by the application itself.
If, in the same example, the permission attribute was set to a permission declared
elsewhere (such asandroid.permission.CALL_EMERGENCY_NUMBERS, it would not
have been necessary to declare it again with a <permission> element. However, it would
still have been necessary to request its use with <uses-permission>.

35

The <permission-tree> element declares a namespace for a group of permissions that will be defined in
code. And <permission-group> defines a label for a set of permissions (both those declared in the manifest
with <permission> elements and those declared elsewhere). It affects only how the permissions are grouped
when presented to the user. The <permission-group> element does not specify which permissions belong to
the group; it just gives the group a name. A permission is placed in the group by assigning the group name
to the <permission> element's permissionGroup attribute

36

Other Classes Used In Development


public class

ConnectivityManager
extends Object
java.lang.Object
android.net.ConnectivityManager

Class Overview

Class that answers queries about the state of network connectivity. It also notifies
applications when network connectivity changes. Get an instance of this class by
callingContext.getSystemService(Context.CONNECTIVITY_SERVICE).
The primary responsibilities of this class are to:
1.
2.
3.
4.

Monitor network connections (Wi-Fi, GPRS, UMTS, etc.)


Send broadcast intents when network connectivity changes
Attempt to "fail over" to another network when connectivity to a network is lost
Provide an API that allows applications to query the coarse-grained or finegrained state of the available networks
Public Methods
NetworkInfo

getActiveNetworkInfo()
Returns details about the currently active data network.

NetworkInfo[
]

getAllNetworkInfo()

boolean

getBackgroundDataSetting()
This method was deprecated in API level 14. As
of ICE_CREAM_SANDWICH, availability of background data
depends on several combined factors, and this method will
always return true. Instead, when background data is
unavailable,getActiveNetworkInfo() will now appear
disconnected.

NetworkInfo

getNetworkInfo(int networkType)

int

getNetworkPreference()

37

boolean

isActiveNetworkMetered()
Returns if the currently active data network is metered.

static boolean

isNetworkTypeValid(int networkType)

boolean

requestRouteToHost(int networkType, int hostAddress)


Ensure that a network route exists to deliver traffic to the
specified host via the specified network interface.

void

setNetworkPreference(int preference)

int

startUsingNetworkFeature(int networkType, String feature)


Tells the underlying networking system that the caller wants to
begin using the named feature.

int

stopUsingNetworkFeature(int networkType, String feature)


Tells the underlying networking system that the caller is finished
using the named feature.

[Expand]
Inherited Methods
From class java.lang.Object

38

Dialogs
A dialog is a small window that prompts the user to make a decision or enter additional
information. A dialog does not fill the screen and is normally used for modal events that
require users to take an action before they can proceed.

Dialog Design
For information about how to design your dialogs, including recommendations for
language, read the Dialogs design guide.

The Dialog class is the base class for dialogs, but you should avoid
instantiating Dialog directly. Instead, use one of the following subclasses:
AlertDialog
A dialog that can show a title, up to three buttons, a list of selectable items, or a
custom layout.
DatePickerDialog or TimePickerDialog

A dialog with a pre-defined UI that allows the user to select a date or time.

39

Toasts
A toast provides simple feedback about an operation in a small popup. It only fills the
amount of space required for the message and the current activity remains visible and
interactive. For example, navigating away from an email before you send it triggers a
"Draft saved" toast to let you know that you can continue editing later. Toasts
automatically disappear after a timeout.

If user response to a status message is required, consider instead using a Notification.


public class

WifiManager.WifiLock
extends Object
java.lang.Object
android.net.wifi.WifiManager.WifiLock

Class Overview

Allows an application to keep the Wi-Fi radio awake. Normally the Wi-Fi radio may turn
off when the user has not used the device in a while. Acquiring a WifiLock will keep the
radio on until the lock is released. Multiple applications may hold WifiLocks, and the
radio will only be allowed to turn off when no WifiLocks are held in any application.
40

Before using a WifiLock, consider carefully if your application requires Wi-Fi access, or
could function over a mobile network, if available. A program that needs to download
large files should hold a WifiLock to ensure that the download will complete, but a
program whose network usage is occasional or low-bandwidth should not hold a
WifiLock to avoid adversely affecting battery life.
Note that WifiLocks cannot override the user-level "Wi-Fi Enabled" setting, nor Airplane
Mode. They simply keep the radio from turning off when Wi-Fi is already on but the
device is idle.
Any application using a WifiLock must request
the android.permission.WAKE_LOCK permission in an<uses-permission> element of the
application's manifest.

Summary

Public Methods
void

acquire()
Locks the Wi-Fi radio on until release() is called.

boole
an

isHeld()
Checks whether this WifiLock is currently held.

void

release()
Unlocks the Wi-Fi radio, allowing it to turn off when the device
is idle.

void

setReferenceCounted(boolean refCounted)
Controls whether this is a reference-counted or nonreference-counted WifiLock.

void

setWorkSource(WorkSource ws)

String

toString()
Returns a string containing a concise, human-readable
description of this object.

41

public class

WifiInfo
extends Object
implements Parcelable
java.lang.Object
android.net.wifi.WifiInfo

Class Overview

Describes the state of any Wifi connection that is active or is in the process of being set
up.

Summary
Constants
Stri
ng

LINK_SPEED_U
NITS

Link speed in Mbps

[Expand]
Inherited Constants
From interface android.os.Parcelable

Public Methods
String

getBSSID()
Return the basic service set identifier (BSSID)
of the current access point.

static NetworkInfo.DetailedSta
te

getDetailedStateOf(SupplicantState suppState)
Map a supplicant state into a fine-grained
network connectivity state.

boolean

getHiddenSSID()

int

getIpAddress()

int

getLinkSpeed()
Returns the current link speed
in LINK_SPEED_UNITS.

String

getMacAddress()
42

int

getNetworkId()
Each configured network has a unique small
integer ID, used to identify the network when
performing operations on the supplicant.

int

getRssi()
Returns the received signal strength indicator
of the current 802.11 network.

String

getSSID()
Returns the service set identifier (SSID) of the
current 802.11 network.

SupplicantState

getSupplicantState()
Return the detailed state of the supplicant's
negotiation with an access point, in the form of
a SupplicantState object.

43

Debugging In Eclipse

1.1. What is debugging?


Debugging allows you to run a program interactively while watching the source code
and the variables during the execution.
Via breakpoints in the source code you specify where the execution of the program
should stop. To stop the execution only if a field is read or modified, you can
specify watchpoints.
Breakpoints and watchpoints can be summarized as stop points.
Once the program is stopped you can investigate variables, change their content, etc.
1.2. Debugging support in Eclipse
Eclipse allows you to start a Java program in Debug mode.
Eclipse has a special Debug perspective which gives you a preconfigured set of views.
In this perspective you control the execution process of your program and can
investigate the state of the variables.
2. Prerequisites
The following assumes you know how to develop simple standard Java programs.
This article will focus on how to debug Java applications in Eclipse.
The installation and usage of Eclipse as Java IDE is described in Eclipse Java IDE
Tutorial .
3. Debugging in Eclipse
3.1. Setting Breakpoints
To set breakpoints in your source code right-click in the small left margin in your
source code editor and selectToggle Breakpoint. Alternatively you can double-click on
this position.

44

For example in the following screenshot we set a breakpoint on the


line Counter counter = new Counter();.

Starting the Debugger


To debug your application, select a Java file which can be executed, right-click on it
and select Debug As Java Application.

45

After you have started the application once via the context menu, you can use the created
launch configuration again via the Debug button in the the Eclipse toolbar.

If you have not defined any breakpoints, this will run your program as normal. To debug
the program you need to define breakpoints.

46

Android & Walky


Navigating To Walky(Getting Started)
1.Home Screen

2.Find Walky In App3.Walky


Drawer

Walky is still an Android APP and hence to get your it work you need to follow normal
Android navigations i.e. HomeApp DrawerWalky
Walky works healthy on LAN Your Phone Must be connected to an Access Point or
Wifi-Hot Spot.

47

Way To Be Connected:
What is an Access Point?
In computer networking, a wireless access point (AP) is a device that allows wireless
devices to connect to a wired network using Wi-Fi, or related standards. The AP usually
connects to a router (via a wired network) if it's a standalone device, or is part of a router
itself.

Connection to Access Point :Ensure that you have your wifi On on your device and your
handset must support that of course. Once you have connected to your Access point you r
ready to use Walky. Walky doesnt need any Internet connection as the basic need to
work is in LAN

Tethering(Portable Wifi hot spot)


Android Operating system come with a more sophisticated feature that an Android phone
could act as an Access point or wifi router. And one can use Accesss points 3G, 2G
connection and run Internet on the connected client Android Phone.
Most of the device which are wifi (Wireless Fidelity ) can be made Portable
wifi-hotspot.

What a Walky want is a common access point where all Walky clients are connected.
Onces connected Device are assigned an IP address which needs to exchanged when
communicating.
Note: Walky Helps In Establishing Communication Channel. It does not Communicate on
behalf of User. User must be smart enough to use it optimum & intelligently convey Half
duplex communication.

48

How to Tether?
One device can can take atmost 5 connection. And also the device which will act as an
access point will not be used for communication by user.
The reason for this is that an Android Device cannot act wifi client and server at same
time.

Go to Settings More Tethering & portable hotspot

TO Configure : Select Setup Wifi Edit name and password and type of Security
To Enable Tether Just check on Portable Wi-fi hotspot.
49

Diagrammatic Overview
System Overview:

Walky

Receiver
Service
Sender Activity
Class Name:
Con_Activity.java

Class Name:
Wservice.java

Two main threads are running in Walky which take care of both way communication.
One of which is an activity which is visible on the screen and take care of Out Bound
messages.
Second is a Service which is responsible for Inbound or Incoming messages. Reason for
the receiver to be a Service class has its own importance. An Activity remains running on
a system even if it is not Visible until demand for resources rise. Once demands rises
need for memory increases and in such case Activities in background are stoped.
But a Service remains in system running even if that application is closed. Hence Service
was a reasonable choice in selecting a receiver class.

50

Activity: Con_Activity

As Form is for Dotnet; JFrame is for Java, similarly an Activity is for Android.
Activity =Activity.java + activity.xml
This Activity take care of outbound messages of Walky. It tries to establish connection
with Reciver Services (wservice) for Walky.
Soon we will see some more diagrammatic representation of this class. Also what are
those multi-threads running in background all together toward same goal.
Let us see Top View of this Activity called Con_Activity.

51

Con_Activity Representation

Start

Check System Wifi-Interface and aquire wifi interface IP


Idle

Access SD card locate file .


OFF
Connect to remote socket and send audio file.
Toggled on

ON

Audio From user accessing mic.


UntilRecord
Off
Encoding , Storing
Accessing SD Card.

The above diagram constitutes the State Transition Diagrams of Con_Activity. As


mentioned before Sending of messages and receiving of messages are just totally
different things. Sending and receiving are Independents of each other.
Following Segmets Describe about Service of Walky. Service is responsible for receiving
or listening connection and playing them to user.

52

WService (Android Service) Representations

Listening
Incoming network connection

YES

NO

Receive File
Access Sdcard and Store File

Play

The above diagram constitutes the State Transition Diagrams of Service named
wservice. Here we can see that initially receiver is continuously in a listening state.
This continue to be same until and external socket connection is interrupt on the system
at same port on which Walkys wservice is running. Once connection is established but
obvious audio message is received and stored at some predefined location. Now after
receiving current thread again returns to listening state. A new thread is initiated which
access received file location and play for the user to listen. Hence again Service is ready
to receive new message.
Now lets move to Building Blocks to Walky.

53

Building Blocks:
One way of Solving Problem Statement is to break the problem in smaller
problems and then individually solving them might solve the bigger gaint problem.
Same problem solving scheme has been use in Walky. Apart from learning Android
System and Java Platform four basic ideas have inspired development of Walky.

SR
te o c r e
F i l e
o
IIPo nn r dtd e i rr en ca t l l yo
r
SSl
ee
t u
p
uC
ESR
xsodeur eetccd eak i rte ne t a a l
nA
aeo pie v er va ek re S r os
sSM
.c
k
e
m
o
r
y
a
Ty
C
P
/ I P
A
eaeFF ii tbc ll ae cl u e e s sti nos g
c
o
n
n
e
n
t i
Fja a i c l ev ec da e .i san s e
M
t
ve
i t y .
PLm il bae ryd a e i ra r y
o
f
U
s
e
J a
v
a
A
Sr e tn co d or re r o d iF ed i l r e o
f
. n
e
t
sLA yo n sc d ta re lo lm yi d. .
L
i b
r a
r y
s
y
s
t e
m
.
I n
d
i r e
c
t l y
u
s
e
m
i c
.

Assembly of these building blocks have resulted in Walky. But off course there are
various methods to assemble these Blocks which we will discuss in next segment of this
book.
Note: I have tried many more methods to make a working model of Walky but
unfortunately each method had some loop hole or inefficiency. Current version is
acceptably balanced but it still lack Full Duplex Communication. All we need is
continuous steaming of message as and when said. But currently Recording and Sending
at same time is a Thorn in a Neck issue.
All the different approaches tried to made APP will be discussed later.

54

Walky Manifest File


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="col.project.walky"
android:versionCode="1"
android:versionName="1.0" >
<uses-permission
android:name="android.permission.WRITE_INTERNAL_STORAGE" />
<uses-permission
android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" >
</uses-permission>
<uses-permission android:name="android.permission.CLEAR_APP_CACHE"
/>
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission
android:name="android.permission.ACCESS_WIFI_STATE"
android:required="true" />
<uses-permission
android:name="android.permission.CHANGE_WIFI_STATE"
android:required="true" />
<uses-permission
android:name="android.permission.INTERNET"
android:required="true" />
<uses-permission
android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-feature android:name="android.hardware.wifi" />
<uses-feature
android:name="android.permission.WI-FI"
android:required="true" />
<uses-sdk
android:minSdkVersion="10"
android:targetSdkVersion="14" />
<application
android:name="col.project.walky.MyApplication"
android:allowBackup="true"
android:debuggable="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="col.project.walky.Con_Activity"
android:screenOrientation="portrait"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category
android:name="android.intent.category.LAUNCHER" />
</intent-filter>

55

</activity>
<activity
android:name="col.project.walky.CallActivity"
android:label="@string/title_activity_call" >
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="col.project.Con_Activity" />
</activity>
<service
android:name="col.project.walky.WService"
android:enabled="true"
android:process=":wreciver" >
</service>
<service
android:name="col.project.walky.WalkySevice"
android:enabled="true"
android:process=":wsender" />
<service android:name="col.project.walky.RecorderService"
android:enabled="true"
android:process=":wrecorder"/>
<activity
android:name="col.project.walky.ConversationActivity"
android:label="@string/app_name" >
</activity>
</application>
</manifest>

56

Class HandsOn.java:
This class is a helper class of project. As Need for some commonly used Functions and
variable increased need for some generalize space and scope rised. And hence this helper
class came into exsistence
Following are some snippets from Class HandOn.java
//Check online status of device
public static boolean isOnline(Context context ) {
WifiManager wifi;
Ip="";
Mac="";
RemoteIp="192.168.1.4";
Port =12345;
RemotePort=12345;
Status="";
try{
ConnectivityManager connMgr =
(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY
_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
Log.d("Network Status:::",networkInfo.getDetailedState().toString());
//toastit(networkInfo.getDetailedState().toString());
wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
WifiInfo wi= wifi.getConnectionInfo();
String ip=Formatter.formatIpAddress(wi.getIpAddress());
Ip=ip;
Mac=wi.getMacAddress().toString();
// Just to Create Folder n file
//toastit("IP"+ip);
//toastit("Mac"+wi.getMacAddress().toString());
return (networkInfo != null && networkInfo.isConnected());
}catch(Exception e)
{
Log.e(handsOn.Tag,"HandsONException:"+e);
Ip="NO Connectivity";
return false;
}

57

public static String getCurrentIP()


{
WifiManager wifi;
try{
ConnectivityManager connMgr =
(ConnectivityManager)MyApplication.getAppContext().getSystemServi
ce(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
Log.d("Network Status:::",networkInfo.getDetailedState().toString());
//toastit(networkInfo.getDetailedState().toString());
wifi = (WifiManager)
MyApplication.getAppContext().getSystemService(Context.WIFI_SERVI
CE);
WifiInfo wi= wifi.getConnectionInfo();
String ip=Formatter.formatIpAddress(wi.getIpAddress());
return ip;
}catch(Exception e)
{
Log.e(handsOn.Tag,"HandsONException:"+e);
Ip="NO Connectivity";
return null;
}
}

Function to Show any ToastMessages.


public static void toastit(String text)
{
try{
//Context context = MyApplication.getAppContext();
Toast.makeText(MyApplication.getAppContext(), text,
Toast.LENGTH_LONG).show();
}catch(Exception e)
{Log.d("Toastit","Exception in Toasit defination:"+e);
}
}

58

Using the Android Emulator

The Android SDK includes a virtual mobile device emulator that runs on your computer.
The emulator lets you prototype, develop and test Android applications without using a
physical device.
The Android emulator mimics all of the hardware and software features of a typical
mobile device, except that it cannot place actual phone calls. It provides a variety of
navigation and control keys, which you can "press" using your mouse or keyboard to
generate events for your application. It also provides a screen in which your application is
displayed, together with any other active Android applications.

To let you model and test your application more easily, the emulator utilizes Android
Virtual Device (AVD) configurations. AVDs let you define certain hardware aspects of
your emulated phone and allow you to create many configurations to test many Android
platforms and hardware permutations. Once your application is running on the emulator,
it can use the services of the Android platform to invoke other applications, access the
network, play audio and video, store and retrieve data, notify the user, and render
graphical transitions and themes.

59

The emulator also includes a variety of debug capabilities, such as a console from which
you can log kernel output, simulate application interrupts (such as arriving SMS
messages or phone calls), and simulate latency effects and dropouts on the data network.
Overview

The Android emulator is an application that provides a virtual mobile device on which
you can run your Android applications. It runs a full Android system stack, down to the
kernel level, that includes a set of preinstalled applications (such as the dialer) that you
can access from your applications. You can choose what version of the Android system
you want to run in the emulator by configuring AVDs, and you can also customize the
mobile device skin and key mappings. When launching the emulator and at runtime, you
can use a variety of commands and options to control its behavior.
The Android system images available through the Android SDK Manager contain code
for the Android Linux kernel, the native libraries, the Dalvik VM, and the various
Android packages (such as the Android framework and preinstalled applications). The
emulator provides dynamic binary translation of device machine code to the OS and
processor architecture of your development machine.
The Android emulator supports many hardware features likely to be found on mobile
devices, including:

An ARMv5 CPU and the corresponding memory-management unit (MMU)

A 16-bit LCD display

One or more keyboards (a Qwerty-based keyboard and associated Dpad/Phone


buttons)
A sound chip with output and input capabilities
Flash memory partitions (emulated through disk image files on the development
machine)

A GSM modem, including a simulated SIM Card

A camera, using a webcam connected to your development computer.

Sensors like an accelerometer, using data from a USB-connected Android device.

The following sections describe the emulator and its use for development of Android
applications in more detail.
Android Virtual Devices and the Emulator
60

To use the emulator, you first must create one or more AVD configurations. In each
configuration, you specify an Android platform to run in the emulator and the set of
hardware options and emulator skin you want to use. Then, when you launch the
emulator, you specify the AVD configuration that you want to load.
Each AVD functions as an independent device, with its own private storage for user data,
SD card, and so on. When you launch the emulator with an AVD configuration, it
automatically loads the user data and SD card data from the AVD directory. By default,
the emulator stores the user data, SD card data, and cache in the AVD directory.
To create and manage AVDs you use the AVD Manager UI or the android tool that is
included in the SDK. For complete information about how to set up AVDs, see Managing
Virtual Devices.
Starting and Stopping the Emulator

During development and testing of your application, you install and run your application
in the Android emulator. You can launch the emulator as a standalone application from a
command line, or you can run it from within your Eclipse development environment. In
either case, you specify the AVD configuration to load and any startup options you want
to use, as described in this document.
You can run your application on a single instance of the emulator or, depending on your
needs, you can start multiple emulator instances and run your application in more than
one emulated device. You can use the emulator's built-in commands to simulate GSM
phone calling or SMS between emulator instances, and you can set up network
redirection that allows emulators to send data to one another. For more information,
see Telephony Emulation, SMS Emulation, and Emulator Networking
To start an instance of the emulator from the command line, navigate to the tools/ folder
of the SDK. Enter emulatorcommand like this:
emulator -avd <avd_name> [<options>]
This initializes the emulator, loads an AVD configuration and displays the emulator
window. For more information about command line options for the emulator, see
the Android Emulator tool reference.

61

Note: You can run multiple instances of the emulator concurrently, each with its own
AVD configuration and storage area for user data, SD card, and so on.
If you are working in Eclipse, the ADT plugin for Eclipse installs your application and
starts the emulator automatically, when you run or debug the application. You can specify
emulator startup options in the Run/Debug dialog, in the Target tab. When the emulator is
running, you can issue console commands as described later in this document.
If you are not working in Eclipse, see Installing Applications on the Emulator for
information about how to install your application.
To stop an emulator instance, just close the emulator's window.
Emulator Networking

The emulator provides versatile networking capabilities that you can use to set up
complex modeling and testing environments for your application. The sections below
introduce the emulator's network architecture and capabilities.
Network Address Space
Each instance of the emulator runs behind a virtual router/firewall service that isolates it
from your development machine's network interfaces and settings and from the internet.
An emulated device can not see your development machine or other emulator instances
on the network. Instead, it sees only that it is connected through Ethernet to a
router/firewall.
The virtual router for each instance manages the 10.0.2/24 network address space all
addresses managed by the router are in the form of 10.0.2.<xx>, where <xx> is a number.
Addresses within this space are pre-allocated by the emulator/router as follows:
Network Address

Description

10.0.2.1

Router/gateway address

10.0.2.2

Special alias to your host loopback interface (i.e., 127.0.0.1 on


your development machine)

10.0.2.3

First DNS server

10.0.2.4 /
10.0.2.5 / 10.0.2.6

Optional second, third and fourth DNS server (if any)

10.0.2.15

The emulated device's own network/ethernet interface


62

127.0.0.1

The emulated device's own loopback interface

Note that the same address assignments are used by all running emulator instances. That
means that if you have two instances running concurrently on your machine, each will
have its own router and, behind that, each will have an IP address of 10.0.2.15. The
instances are isolated by a router and can not see each other on the same network. For
information about how to let emulator instances communicate over TCP/UDP,
see Connecting Emulator Instances.
Also note that the address 127.0.0.1 on your development machine corresponds to the
emulator's own loopback interface. If you want to access services running on your
development machine's loopback interface (a.k.a. 127.0.0.1 on your machine), you should
use the special address 10.0.2.2 instead.
Finally, note that each emulated device's pre-allocated addresses are specific to the
Android emulator and will probably be very different on real devices (which are also very
likely to be NAT-ed, i.e., behind a router/firewall)
Local Networking Limitations
Android applications running in an emulator can connect to the network available on
your workstation. However, they connect through the emulator, not directly to hardware,
and the emulator acts like a normal application on your workstation. This means that the
emulator, and thus your Android applications, are subject to some limitations:

Communication with the emulated device may be blocked by a firewall program


running on your machine.

Communication with the emulated device may be blocked by another (physical)


firewall/router to which your machine is connected.

The emulator's virtual router should be able to handle all outbound TCP and UDP
connections/messages on behalf of the emulated device, provided your development
machine's network environment allows it to do so. There are no built-in limitations on
port numbers or ranges except the one imposed by your host operating system and
network.
Depending on the environment, the emulator may not be able to support other protocols
(such as ICMP, used for "ping") might not be supported. Currently, the emulator does not
support IGMP or multicast.
Using Network Redirection
To communicate with an emulator instance behind its virtual router, you need to set up
network redirection on the virtual router. Clients can then connect to a specified guest
63

port on the router, while the router directs traffic to/from that port to the emulated
device's host port.
To set up the network redirection, you create a mapping of host and guest ports/addresses
on the the emulator instance. There are two ways to set up network redirection: using
emulator console commands and using the ADB tool, as described below.
Setting up Redirection through the Emulator Console
Each emulator instance provides a control console the you can connect to, to issue
commands that are specific to that instance. You can use the redir console command to
set up redirection as needed for an emulator instance.
First, determine the console port number for the target emulator instance. For example,
the console port number for the first emulator instance launched is 5554. Next, connect to
the console of the target emulator instance, specifying its console port number, as
follows:
telnet localhost 5554
Once connected, use the redir command to work with redirection. To add a redirection,
use:
add <protocol>:<host-port>:<guest-port>
where <protocol> is either tcp or udp, and <host-port> and <guest-port> sets the mapping
between your own machine and the emulated system, respectively.
For example, the following command sets up a redirection that handles all incoming TCP
connections to your host (development) machine on 127.0.0.1:5000 and will pass them
through to the emulated system's 10.0.2.15:6000.:
redir add tcp:5000:6000
To delete a redirection, you can use the redir del command. To list all redirection for a
specific instance, you can use redir list. For more information about these and other
console commands, see Using the Emulator Console.
Note that port numbers are restricted by your local environment. this typically means that
you cannot use host port numbers under 1024 without special administrator privileges.
64

Also, you won't be able to set up a redirection for a host port that is already in use by
another process on your machine. In that case, redir generates an error message to that
effect.
Setting Up Redirection through ADB
The Android Debug Bridge (ADB) tool provides port forwarding, an alternate way for
you to set up network redirection. For more information, see Forwarding Ports in the
ADB documentation.
Note that ADB does not currently offer any way to remove a redirection, except by
killing the ADB server.
Configuring the Emulator's DNS Settings
At startup, the emulator reads the list of DNS servers that your system is currently using.
It then stores the IP addresses of up to four servers on this list and sets up aliases to them
on the emulated addresses 10.0.2.3, 10.0.2.4, 10.0.2.5 and 10.0.2.6 as needed.
On Linux and OS X, the emulator obtains the DNS server addresses by parsing the
file /etc/resolv.conf. On Windows, the emulator obtains the addresses by calling
the GetNetworkParams() API. Note that this usually means that the emulator ignores the
content of your "hosts" file (/etc/hosts on Linux/OS X, %WINDOWS
%/system32/HOSTS on Windows).
When starting the emulator at the command line, you can also use the -dns-server
<serverList> option to manually specify the addresses of DNS servers to use, where
<serverList> is a comma-separated list of server names or IP addresses. You might find
this option useful if you encounter DNS resolution problems in the emulated network (for
example, an "Unknown Host error" message that appears when using the web browser).

65

How to Use Walky


Following are the basic step to run Walky at your home network or LAN.
1.Connect to Access Point

2.Exchange IPs

66

3.Press Toggle(ON Button) and Speakagain OFF to send your Message.


Limitations Future Enhancements
As we know that Walky is not a stable version and is still in BETA stage. In Other word
Buggy. Limitation of current APP are enhancement for future.
Work In Progress:

Walky though is able to transport message well but due to some lack of Research is has
some bad standards of validation.
In some cases typing the wrong IP and then trying to connect may may not notifiy you
what mistake you have made. Hence there is need for more user friendliness along with
simple and optimized behavior.
Along with this there is a need for Full Duplex communication need which this APP
currently does not satisfy. A very importance is been given to this feature and will be
available in near future.
Hence Walky will fully Function as IP Phone
Extend right from LAN to WAN
Walky works on IP address or we can say sockets with fixed port numbers. Hence
if given a proper IP and receiver running on required port number one can establish a
connection.
According to MyPublic
Research
and Development (Made a Dummy Receiver running on my
IP
pc).with some proper NATing efforts I was able to communicate via Public Ip Address
though it was not two way proper communication at all but gave a sign of connectivity
clear enough.
NAT

To NATing into android again some deep research has to be carried out.

Public IP

NAT

WAN

67

Chat Integration
Though Walky solely works on Speech concept but something extra like chat will
support the user out of his way. More than one channel or mode for communitation will
not only make to communicate in a robust way but also gracefully make APP robust in
turn.
Currently Walkys Chat Integration is in Development mode. As it was Voice same is the
case with Chat. Just to an extension is a chat LOG file which keep track of data
exchanged between user.
As Walky is LAN based and people are not foolish to use chat application when sitting
around. But in Offices or any event management occation their might come a condition to
convey message quietly. So for that, user might use any other message alternative to do
so. Walky will do this for them as well.

68

Same System Overview holds for Chat application

Walky-Chat

Receiver
Service
Sender Activity
Class Name:
Converstional_Activity.java

Class Name:
WalkyService.java

Two main threads are running in Walky which take care of both way communication.
One of which is an activity which is visible on the screen and take care of Out Bound
messages.
Second is a Service which is responsible for Inbound or Incoming messages. Reason for
the receiver to be a Service class has its own importance. An Activity remains running on
a system even if it is not Visible until demand for resources rise. Once demands rises
need for memory increases and in such case Activities in background are stoped.
But a Service remains in system running even if that application is closed. Hence Service
was a reasonable choice in selecting a receiver class.

69

Full Duplex Concept

Sender:
Call Live

Yes
NO
IDLE

Call
Thread:
Recording for so
Sent to remote site

Repeat

As you can see here same procedure is been carried out here. But except whole file pieces
of files are sent in Real Time.
Difficulty with this approach is that recording thread must be timed and synchronized so
that there is minimum jitter in the pieces of audio. Say 10 micro seconds between two
file.
Receiver:
Listening

From Sender

Play

Storage
Receive the file in some order.

Concatinate some files

70

Threa
Sm

if(socket.isConnected())
{
Log.d(handsOn.Tag, "Walky Service connected to :"+socket.getInetAddress());
int i=0;
while(i<15)
{
File f=new File(Environment.getExternalStorageDirectory() + "/walky
Folder/file"+i+".wav");
Thread.sleep(50);
new RecordThread(f).start();
Thread.sleep(1000);//3000
//Send file
i++;
}//while ends
int j=0;
while(j<15)
{
File fp1=new File(Environment.getExternalStorageDirectory() + "/walky
Folder/file"+j+".wav");
for (i=j;i<j+5;i++)
{
File sample=new File(Environment.getExternalStorageDirectory() +
"/walky Folder/file"+i+".wav");
fp1=ConcatAudio.confile(fp1, sample);
}
Thread.sleep(10);
new PlayRecieved(fp1).start();
Thread.sleep(5000);//2900;100;
j=j+5;
}//while ends
Log.d(handsOn.Tag, "WalkySevice Finished playing:");
}//if ends
}catch(Exception e){Log.d(handsOn.Tag, "WalkySevice Error:"+e);}//trycatch
}//run
}).start();

71

Another approach:
Use Parcel File Descriptor:
In this approach we directly write out recorded bit stream on Socket. And
Read is Directly from socket .
This Concept might be very easy to Imagine but is most difficult to
Implement.
Sender:
Record and write on socket
Send

Call Live

Receiver:

Receive and Read from socket


Play

Call Live

72

Conclusion

Hence the problem statement of a need of an APP for Android user communicate
within LAN.
Development of and APP simulating Legacy Walky Talky.
Uses of minimum hardware requirement and also low end device support.
Support from Android Version 2.3 till 4.0 and above.
Apart from all these research gave many byproduct knowledge associated by
Android.
Rooted and UnRooted Phones
Locked and Unlock Bootloader
Flashing ROMs
Flashing Apps
Backup and Restore Systems
Etc

Reference

http://www.vogella.com/articles/Android/article.html
developer.android.com/
http://stackoverflow.com/questions/
http://prasanta-paul.blogspot.in/2010/06/android-parcelable-example.html
http://dev.fyicenter.com/Interview-Questions/Socket2/What_s_File_Descriptors_and_Sockets_.html
http://www.mastertheboss.com/jboss-configuration/solving-javanetbindexceptionaddress-already-in-use-jvm_bind
http://android-er.blogspot.in/2011/01/simple-communication-using.html
and other Internet Videos Tutorial
www.youtube.com

Book
Java 2 Complete Reference

73

You might also like