57% found this document useful (7 votes)
3K views58 pages

Blutooth Chat Project Report

after completing the six month training we need to have this type of report that we have to show at our university.this report is based on android app Bluetooth chat .

Uploaded by

Deven Rathore
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
57% found this document useful (7 votes)
3K views58 pages

Blutooth Chat Project Report

after completing the six month training we need to have this type of report that we have to show at our university.this report is based on android app Bluetooth chat .

Uploaded by

Deven Rathore
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 58

1

(Project Name: Royal Bluetooth Chat)




N.C COLLEGE OF ENGINEERING & TECHNOLOGY
N.C.INSTITUTE OF COMPUTER SCIENCE
(TECHNICAL CAMPUS)
ISRANA, (PANIPAT-132103)
In partial fulfillment of Requirement for the M.C.A.

Submitted To: - Submitted By:-
Mrs. Deepika Sareen Anil Kumar
(Lect. Of M.C.A.) MCA/11/45
2

CONTENTS PAGE FOR SYNOPSIS

S.NO. Particular PAGENO.

1. ACKNOWLEDGEMENT 3
2. ABOUT TRAINING AND CONTACT INFORMATION 4
3. COMPANY PROFILE 5
4. PROJECT INTRODUCTION 7
5. FEASIBILITY STUDY 10
6. DESIGN PHASE 13
7. IMPLEMENTATION 17
8. TESTING 55
9. CONCLUSION 56
10. FUTURE SCOPE 57
11. BIBLIOGRAPHY 58








3

1. ACKNOWLEDGEMENT

I am highly grateful to Mr. Rohit Anand TPO, N.C. Institute of Computer Science, Israna for
providing this opportunity to carry out the Six Months Industrial Training at Beta soft systems
Pvt. Ltd. at Panchkula.
I would like to expresses my gratitude to other faculty members of Computer Science and
special thanks to Mrs. Deepika Sareen (Sr. Lect. of M.C.A.) of NCICS, Israna for providing
academic inputs, and encouragement throughout this period.
I would like to express a deep sense of gratitude and thank to Mrs. Shambhavi Shulka,
Supervisor Training without whose wise counsel and able guidance, it would have not been
possible to carry out my report in this manner.
Finally, I express my indebtedness to all who have directly or indirectly contributed to the
successful completion of my synopsis report.

Anil Kumar











4

2. ABOUT TRAINING AND CONTACT INFORMATION

For the period from 15 Jan.,2014 to 30 April., 2014
Name of company & address BetaSoftSystems Pvt.Ltd
SEO-398, Sector-20 ,Panchkula(HR)
Department/section in which Training going on Java +Android
Training timings 02:30 PM to 06:00 PM
Break 04:30 PM to 04:45 PM
Training managers name and designation Mrs. Shambhavi Shukla
Company Manager
Training managers contact phone 8288078265
Contact phone of student: In company 094663-92898
: At residence 098969-39400
E-mail Id of student [email protected]
[email protected]
Training Days First 5days (MONDAY TO FRIDAY)
Off days Last 2 days
Project report: Alloted
Training Guider Name : Miss Akanksha Sharma
Designation : Trainer.
Plateform : Java
E-mail:[email protected]
Mobile:-7355537342

5

3. COMPANY PROFILE (BETA SOFT SYSTEM)


Establishment:
Established in 2005, by Ritu and Vishal Mangla, Beta Soft Systems Inc is an AmericanIndian
IT Staffing & Consulting Company headquartered in Fremont California, USA. We are one of
the most promising companies in the Silicon Valley for staffing, consulting and technology
solutions with revenues of over US$ 20 million (FY13), and a workforce of over 350 people.
Working and Processing:
Beta Soft Systems is recognized for its high quality staffing
solutions, lean consulting methodologies and Information Technology implementation for
Fortune 500 Companies. We deliver comprehensive IT solutions for small and medium
businesses and deliver top talent for fixed time projects of large companies. We also have an
outsourcing model that enables our clients to offload full responsibility of project deliverables to
our in-house talent.
Beta Soft Systems unwavering commitment to its clients
profitability has been the crux of our 4P strategy. We focus on Product, Process, Portal and
Public Relations, the four corner stones of a successful modern day business. Depending on our
clients business model, we target the required function and build resource optimization and
talent management processes and bring about significant revenue impact for our clients.
Beta Soft Systems helps clients in building profitable
business models by leveraging on industry-wide experience, expertise from subject matter
experts, a comprehensive portfolio of services and a scalable revenue sharing business model.
Our large network of dedicated employees and a steady pipeline of the best IT talent enable us to
harness the latest technologies across Industries for delivering unmatched value.


6

Agenda and Motive :
Over 95% of our revenue is driven by our existing client base and
references. This trust bestowed upon us by our clients has resulted in a 100% revenue growth
every year, over the past 4 years. We have the Industry best policies for Service Level
Agreements, Candidate replacement and Delivery turnaround time. All this makes us a
trusted partner of choice for global businesses looking to find top class talent and IT solutions.
Our Companys value system assures our clients of an impeccable track record in maintaining
client confidentiality and respect for their privacy.
We strive to bring the best talent to our clients. Our many years of talent management experience
has helped us develop methodologies and strategies to sort and sift candidates from various
backgrounds. Our robust screening methodology checks for the candidates skills those are both
fundamental to the position and also specific to the industry the candidate is applying to. We
have special knowledge enhancement programs and Knowledge Repositories where candidates
can learn and reapply for client openings. However we ensure that we never solicit our clients
with unsuccessful candidates. In our continuous attempt to deliver high quality, Beta Soft
Systems is now developing a unique scoring mechanism, powered by our weighted metrics
algorithm that we use to score our candidates.










7

4. PROJECT INTRODUCTION

ABSTRACT:
Bluetooth chatting is an innovative approach to the mobile world. This application shows use of
Bluetooth in terms of chatting. Means persons can chat via Bluetooth. The main midlet has just a
list which has two values server and client. By selecting one of these two values, the
corresponding instance is created. Midlet is used to initialize the connection. It does following
thing at here. First, it starts the application and search the Bluetooth device. It sends the signal to
the server class. Second, it can run, pause and stop the application. Third, it shows alert using
setAlert function on every changing. Server class goes active when it go signal from the midlet
class. It sends the hello world string with the string to the other devices. Client class works to
respond the other Bluetooth device server.
Royal Bluetooth chat is a Bluetooth messaging. Royal Bluetooth Chat allows you to see other
Bluetooth Chat users around, ping anyone of them, and create either private chat sessions or
public messaging rooms via Bluetooth. This application allows two Android devices to carry out
two-way text chat over Bluetooth. Start the application from the first screen; splash Screeng and
than go to on home page, where a drawer is used to provide many opportunities to the users .
This is an optional step to provide additional information to other chat buddies. Next, select
Search' option which attempts to discover other users in the area. Detected user-profiles are
listed as selectable boxes. While a profile is selected, Options menu can be used to view profile
details, initiate a file transfer or to refresh list of detected friends.
PROPOSED SYSTEM:
This is a Bluetooth messaging app you can connect and send messages to other android devices
and see Bluetooth compatible devices around you. No GSM or Wi-Fi connection required all
you need is a two Bluetooth compatible android devices in range of each other and you can text
away. If you have internet connection you can also share messages, images and also files in on
Gmail, face-book and other compatible services. To chat with a user, select it from the list and
press Ping' to send a welcome message. The other user may do the same. As the welcome
message is displayed, use right or left soft key to accept or reject the chat session. Once the
session is accepted, the chat starts with colorful text to differentiate users. In addition to this
person-to-person chat, chat rooms can be used to gather a number of buddies.
ADVANTAGE:
All peers that want to communicate should have Royal Bluetooth Chat running.
It is enough that one peer does the initial Search" operation.
Every time a new comer peer does its first "Look for friends" operation, the operation will
reorganize all initial communication and profile sharing stuff.
Every peer will have an updated list of profiles around automatically and the profile list will
be displayed to warn everyone about the new comer.
8
Be aware that if more than one peer do "Look for friends" simultaneously, they might not be
able to see each other (because of Bluetooth running principles)
Be aware that the set up of the profile list might take up to one minute. Therefore be patient.
MODULES:-
Scanning for other Bluetooth devices
This application begins searching for devices as soon as it is opened. Options menu
appear only after a successful or unsuccessful search is complete. Other options are new
message alert - vibrate or sound, and refresh rate setting ranging from 30 seconds to three
minutes. Users can manually refresh the list of users as well. Select a user from the list
and use Options.
Querying the local Bluetooth adapter for paired Bluetooth devices
The Bluetooth Adapter is the entry-point for all Bluetooth interaction. Using this, you can
discover other Bluetooth devices, query a list of bonded (paired) devices, instantiate
a Bluetooth Device using a known MAC address, and create a BluetoothServerSocket to
listen for communications from other devices. Use this to request a connection with a
remote device through a Bluetooth Socket or query information about the device such as
its name, address, class, and bonding state. Represents the interface for a Bluetooth
socket (similar to a TCP Socket). This is the connection point that allows an application
to exchange data with another Bluetooth device via Input Stream and Output Stream.
Establishing RFCOMM channels/sockets
In the socket programming model, a socket represents an endpoint of a communication
channel. Sockets are not connected when they are first created, and are useless until a call
to either connect (client application) or accept (server application) completes
successfully. Once a socket is connected, it can be used to send and receive data until the
connection fails due to link error or user termination.
An RFCOMM Bluetooth Socket used to accept incoming connections must be attached to
operating system resources with the bind method. Bindtakes in a tuple specifying the
address of the local Bluetooth adapter to use and a port number to listen on. Usually,
there is only one local Bluetooth adapter or it doesn't matter which one to use, so the
empty string indicates that any local Bluetooth adapter is acceptable. Once a socket is
bound, a call to listen puts the socket into listening mode and it is then ready to accept
incoming connections.
Connecting to a remote device
You must request the BLUETOOTH permission in order to perform any Bluetooth
communication, such as requesting a connection, accepting a connection, and transferring
data. Before your application can communicate over Bluetooth, you need to verify that
Bluetooth is supported on the device, and if so, ensure that it is enabled. you need to ensure
9
that Bluetooth is enabled. A dialog will appear requesting user permission to enable
Bluetooth. Once a connection is made with a remote device for the first time, a pairing
request is automatically presented to the user. When a device is paired, the basic information
about that device (such as the device name, class, and MAC address) is saved and can be
read using the Bluetooth APIs. Using the known MAC address for a remote device, a
connection can be initiated with it at any time without performing discovery (assuming the
device is within range).
Transferring data over Bluetooth
Check the manual that came with your cellular phone and read the section on Bluetooth
capabilities to see if your phone has a Bluetooth password. Note down the password. Power
on your cellular phone and access the "Settings" option in the main menu. Choose the
"Bluetooth" option if it is immediately available, or choose "Connections" and then
"Bluetooth." Press the option for "Activate Bluetooth.". Repeat the process on the second
phone. Navigate to the folder on your phone that holds the file you want to transfer. Choose
the file and then choose the option to "Send." Press the option to "Send to Phone" and then
press the button to send to a connected Bluetooth phone. Enter in the phone number of the
other phone if your cell does not prompt you to send to an activated Bluetooth phone in
range.

















10



5. FEASIBILITY STUDY OF PROJECT

1. Planning Of Work
The planning idea is a need to handle all the work like database, tables, design, forms, business
logic implementation, development (coding), testing. So to maintain all these we are following a
system development life cycle process in which we have planned these works and stages to make
our work easy like
Analysis and Feasibility Study
Design
a). Analysis and Feasibility Study
# Software Analysis and Technical Feasibility: The software will be made by using the Core
Java Concepts and Java ME, Android SDK, ADT plug-In, XML and SQLite Data Base.
# Schedule Feasibility:- Proposed suited time for making the forms can be approximate 3
months.
The schedule is divided as following
1
st
3 weeks, 7Feb, 2014 to 1March, 2014:- Designing of database and layout of user
interface.SRS design.
1

weeks, 3March, 2014 to 10 March, 2014:- Developing Entity Relationship Diagram (ERDs)
and Data Flow Diagram (DFDs) and designing various logics.
3 weeks, 11 March, 2014 to 1 April, 2014 :- Developing User interface and Database
2 weeks, 2 April, 2014 to 17 April, 2014:- Applying logic to develop code the project. (Coding)
11
4 days, 18 April, 2014 to 22 April, 2014:- Connectivity and work on the presentation layer to
make the project attractive.
3 days, 26 April, 2014 to 23 May, 2014 : -Testing of the project with many techniques or many
android versions.
1 week, 28April, 2014 to 5 May, 2014 : -Documentation.
Work/Week Schedule
7Feb, 2014 to 1March, 2014 DB Design
3March, 2014 to 10 March, 2014 ER-D,DFD
11 March, 2014 to 1 April, 2014 Developing DB and UI
2 April, 2014 to 17 April, 2014 Coding
18 April, 2014 to 22 April, 2014 Presentation Layer
26 April, 2014 to 23 May, 2014 Testing
28April, 2014 to 5 May, 2014 Final Documentation

2. Facilities Required for Project
A. Hardware requirement: Following are the hardware requirements needed for the project:-
Processor : ARM Processor or Intel Processor
System : Pentium IV 2.4GHz
Hard Disk : 40GB
Floppy Disk : 1.44Mb.
Monitor : 15VGA Colors
Ram : 512Mb
Mouse : Logitech.


12


B. Software requirement: Following are the software requirements needed for the project:-
Operating system : Windows XP and above
IDE : Java ME, Eclipse ,SDK and ADT plug-in.
Front end : Android/xml/Adobe Photoshop ,controlled by java
Back end : SqlLite
Development kit : jdk-7
Framework : MVC(Model View Controller)
Tool Kit : Android 2.0 and Above
Documentation : MS Office
DFD and ERD : Smart Draw











13


6.DESIGN PHASE
The purpose of design phase is to plan a solution of the problem specified by the SRS.There are
mainly three phases:-Architecture Design, High level design and Detail design
Architecture design:- It focuses on looking at a system as a combination of many
different components.
DFD of Royal chat:-

High level design:- It identifies the modules that should be built for developing the
system and the specification of these modules.
14



Detail design:- In this, the internal logic of each of the modules is specified

DFD of DataBase:-

15




DFD of Server-Socket:-

DFD of DevicesListActivity:-

16







Database:-

SQLite is a relational database management system contained in a C programming library. In
contrast to other database management systems, SQLite is not a separate process that is accessed
from the client application, but an integral part of it.
SQLite is ACID-compliant and implements most of the SQL standard, using a dynamically and
weakly typed SQL syntax that does not guarantee the domain integrity.
SQLite is a popular choice as embedded database for local/client storage in application software
such as web browsers. It is arguably the most widely deployed database engine, as it is used
today by several widespread browsers, operating systems, and embedded systems, among others.
SQLite has many bindings to programming languages.
17

Features :
SQLite implements most of the SQL-92 standard for SQL but it lacks some features. For
example it has partial support for triggers, and it can't write to views (however it supports
INSTEAD OF triggers that provide this functionality). While it supports complex queries, it still
has limited ALTER TABLE support, as it can't modify or delete columns.
SQLite uses an unusual type system for an SQL-compatible DBMS; instead of assigning a type
to a column as in most SQL database systems, types are assigned to individual values; in
language terms it is dynamically typed. Moreover, it is weakly typed in some of the same ways
that Perl is: one can insert a string into an integer column (although SQLite will try to convert the
string to an integer first, if the column's preferred type is integer). This adds flexibility to
columns, especially when bound to a dynamically typed scripting language. However, the
technique is not portable to other SQL products. A common criticism is that SQLite's type
system lacks the data integrity mechanism provided by statically typed columns in other
products. The SQLite web site describes a "strict affinity" mode, but this feature has not yet been
added.However, it can be implemented with constraints like CHECK(typeof(x)='integer').




7. IMPLEMENTATION

Coding:-
SplashScreen.java:
package com.example.splash_screenn;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.ProgressBar;

public class splash extends Activity {

ProgressBar bar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
bar=(ProgressBar) findViewById(R.id.progressBar1);
bar.setVisibility(View.VISIBLE);
18

Thread thread=new Thread(){
public void run() {
try {
sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
System.out.println("anil singhania");
}

}
};
thread.start();
}

@Override
protected void onPause() {
// TODO Auto-generated method stub
finish();
super.onPause();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

}
XML Layout:-
Fragment_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="com.example.splash_screenn.MainActivity$PlaceholderFragment"
android:background="@drawable/royal1"
>

<ProgressBar
android:id="@+id/progressBar1"
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true" />

19
</RelativeLayout>


Screen Shots:


NavigationDrawer.java
package com.example.royal_chat;

import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.res.Configuration;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class NavigationDrawer extends Activity {

20
private String[] drawerListArray;
private DrawerLayout drawerLayout;
private ActionBarDrawerToggle actionBarDrawerToggle;
ListView drawerlist;
DrawerLayout drawerlayout;
//for dialogbox
ListView blueDialog;
@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_navigation_drawerdemo);
// get list items from strings.xml
drawerListArray = getResources().getStringArray(R.array.items);
// get ListView defined in activity_main.xml
drawerlist = (ListView) findViewById(R.id.left_drawer);

// Set the adapter for the list view
drawerlist.setAdapter(new ArrayAdapter<String>(this,
R.layout.listcontent, drawerListArray));

// 2. App Icon
drawerlayout = (DrawerLayout) findViewById(R.id.drawer_layout);

// 2.1 create ActionBarDrawerToggle
actionBarDrawerToggle = new ActionBarDrawerToggle(
this, /* host Activity */
drawerlayout, /* DrawerLayout object */
R.drawable.draw, /* nav drawer icon to replace 'Up' caret */
R.string.drawer_open, /* "open drawer" description */
R.string.drawer_close /* "close drawer" description */
);

// 2.2 Set actionBarDrawerToggle as the DrawerListener
drawerlayout.setDrawerListener(actionBarDrawerToggle);

// 2.3 enable and show "up" arrow
getActionBar().setDisplayHomeAsUpEnabled(true);

// just styling option
// drawerlayout.setDrawerShadow(R.drawable., GravityCompat.START);

drawerlist.setOnItemClickListener(new DrawerItemClickListener());
}

@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
actionBarDrawerToggle.syncState();
}

@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
21
actionBarDrawerToggle.onConfigurationChanged(newConfig);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {

// call ActionBarDrawerToggle.onOptionsItemSelected(), if it returns true
// then it has handled the app icon touch event

if (actionBarDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}

private class DrawerItemClickListener implements ListView.OnItemClickListener {
@Override
public void onItemClick(AdapterView parent, View view, int position, long id)
{
Toast.makeText(getApplicationContext(), ((TextView)view).getText(),
Toast.LENGTH_LONG).show();
// drawerLayout.closeDrawer(drawerlist);
switch (position) {
case 0:
alertMessage();
break;
}
drawerLayout.closeDrawer(drawerlist);

}
public void alertMessage() {
// TODO Auto-generated method stub

DialogInterface.OnClickListener dialoginterfc=new
DialogInterface.OnClickListener() {

@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
switch (which) {
case DialogInterface.BUTTON_NEGATIVE:
//no button is clicked do nothing
Toast.makeText(getApplicationContext(), "Oh! No",
Toast.LENGTH_LONG).show();
break;
case DialogInterface.BUTTON_POSITIVE:
//Yes Button is clicked
Toast.makeText(getApplicationContext(), "Oh! Yes",
Toast.LENGTH_LONG).show();
break;
}
}
};
//A dialog showing a progress indicator and an optional text message or
view
22
AlertDialog.Builder builder=new
AlertDialog.Builder(getApplicationContext());
builder.setTitle("What you want?
(yes/no)").setNegativeButton("No",dialoginterfc).setPositiveButton("Yes",
dialoginterfc);
builder.setCancelable(false);
builder.show();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}

XML Layout:
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<!-- The main content view -->
<FrameLayout
android:id="@+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<!-- The navigation drawer -->
<ListView
android:id="@+id/left_drawer"
android:layout_width="125dp"
android:layout_height="240dp"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="@android:color/transparent"
android:dividerHeight="0dp"
android:background="#fff000"/>
</android.support.v4.widget.DrawerLayout>

Screen Shot:
23


BluetoothChat.java
package com.example.bluetoothchat;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

/**
* This is the main Activity that displays the current chat session.
*/
24
public class BluetoothChat extends Activity {
// Debugging
private static final String TAG = "BluetoothChat";
private static final boolean D = true;

// Message types sent from the BluetoothChatService Handler
public static final int MESSAGE_STATE_CHANGE = 1;
public static final int MESSAGE_READ = 2;
public static final int MESSAGE_WRITE = 3;
public static final int MESSAGE_DEVICE_NAME = 4;
public static final int MESSAGE_TOAST = 5;

// Key names received from the BluetoothChatService Handler
public static final String DEVICE_NAME = "device_name";
public static final String TOAST = "toast";

// Intent request codes
private static final int REQUEST_CONNECT_DEVICE = 1;
private static final int REQUEST_ENABLE_BT = 2;

// Layout Views
private TextView mTitle;
private ListView mConversationView;
private EditText mOutEditText;
private Button mSendButton;

// Name of the connected device
private String mConnectedDeviceName = null;
// Array adapter for the conversation thread
private ArrayAdapter<String> mConversationArrayAdapter;
// String buffer for outgoing messages
private StringBuffer mOutStringBuffer;
// Local Bluetooth adapter
private BluetoothAdapter mBluetoothAdapter = null;
// Member object for the chat services
private BluetoothChatService mChatService = null;


@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(D) Log.e(TAG, "+++ ON CREATE +++");

// Set up the window layout
requestWindowFeature(Window.FEATURE_ACTION_BAR);
setContentView(R.layout.activity_main);
getWindow().setFeatureInt(Window.FEATURE_ACTION_BAR, R.layout.custom_title);

// Set up the custom title
mTitle = (TextView) findViewById(R.id.title_left_text);
//mTitle.setText(R.string.app_name);
mTitle = (TextView) findViewById(R.id.title_right_text);

// Get local Bluetooth adapter
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
25

// If the adapter is null, then Bluetooth is not supported
if (mBluetoothAdapter == null) {
Toast.makeText(this, "Bluetooth is not available",
Toast.LENGTH_LONG).show();
finish();
return;
}
}

@Override
public void onStart() {
super.onStart();
if(D) Log.e(TAG, "++ ON START ++");

// If BT is not on, request that it be enabled.
// setupChat() will then be called during onActivityResult
if (!mBluetoothAdapter.isEnabled()) {
Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
// Otherwise, setup the chat session
} else {
if (mChatService == null) setupChat();
}
}

@Override
public synchronized void onResume() {
super.onResume();
if(D) Log.e(TAG, "+ ON RESUME +");

// Performing this check in onResume() covers the case in which BT was
// not enabled during onStart(), so we were paused to enable it...
// onResume() will be called when ACTION_REQUEST_ENABLE activity returns.
if (mChatService != null) {
// Only if the state is STATE_NONE, do we know that we haven't started
already
if (mChatService.getState() == BluetoothChatService.STATE_NONE) {
// Start the Bluetooth chat services
mChatService.start();
}
}
}

private void setupChat() {
Log.d(TAG, "setupChat()");

// Initialize the array adapter for the conversation thread
mConversationArrayAdapter = new ArrayAdapter<String>(this, R.layout.message);
mConversationView = (ListView) findViewById(R.id.in);
mConversationView.setAdapter(mConversationArrayAdapter);

// Initialize the compose field with a listener for the return key
mOutEditText = (EditText) findViewById(R.id.edit_text_out);
mOutEditText.setOnEditorActionListener(mWriteListener);
26

// Initialize the send button with a listener that for click events
mSendButton = (Button) findViewById(R.id.button_send);
mSendButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// Send a message using content of the edit text widget
TextView view = (TextView) findViewById(R.id.edit_text_out);
String message = view.getText().toString();
sendMessage(message);
}
});

// Initialize the BluetoothChatService to perform bluetooth connections
mChatService = new BluetoothChatService(this, mHandler);

// Initialize the buffer for outgoing messages
mOutStringBuffer = new StringBuffer("");
}

@Override
public synchronized void onPause() {
super.onPause();
if(D) Log.e(TAG, "- ON PAUSE -");
}

@Override
public void onStop() {
super.onStop();
if(D) Log.e(TAG, "-- ON STOP --");
}

@Override
public void onDestroy() {
super.onDestroy();
// Stop the Bluetooth chat services
//if (mChatService != null) mChatService.stop();
//if(D) Log.e(TAG, "--- ON DESTROY ---");
}

private void ensureDiscoverable() {
if(D) Log.d(TAG, "ensure discoverable");
if (mBluetoothAdapter.getScanMode() !=
BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
Intent discoverableIntent = new
Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,
300);
startActivity(discoverableIntent);
}
}

/**
* Sends a message.
* @param message A string of text to send.
*/
27
private void sendMessage(String message) {
// Check that we're actually connected before trying anything
if (mChatService.getState() != BluetoothChatService.STATE_CONNECTED) {
Toast.makeText(this, R.string.not_connected, Toast.LENGTH_SHORT).show();
return;
}

// Check that there's actually something to send
if (message.length() > 0) {
// Get the message bytes and tell the BluetoothChatService to write
byte[] send = message.getBytes();
mChatService.write(send);

// Reset out string buffer to zero and clear the edit text field
mOutStringBuffer.setLength(0);
mOutEditText.setText(mOutStringBuffer);
}
}

// The action listener for the EditText widget, to listen for the return key
private TextView.OnEditorActionListener mWriteListener =
new TextView.OnEditorActionListener() {
public boolean onEditorAction(TextView view, int actionId, KeyEvent event) {
// If the action is a key-up event on the return key, send the message
if (actionId == EditorInfo.IME_NULL && event.getAction() ==
KeyEvent.ACTION_UP) {
String message = view.getText().toString();
sendMessage(message);
}
if(D) Log.i(TAG, "END onEditorAction");
return true;
}
};

// The Handler that gets information back from the BluetoothChatService
private final Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MESSAGE_STATE_CHANGE:
if(D) Log.i(TAG, "MESSAGE_STATE_CHANGE: " + msg.arg1);
switch (msg.arg1) {
case BluetoothChatService.STATE_CONNECTED:
mTitle.setText(R.string.title_connected_to);
mTitle.append(mConnectedDeviceName);
mConversationArrayAdapter.clear();
break;
case BluetoothChatService.STATE_CONNECTING:
mTitle.setText(R.string.title_connecting);
break;
case BluetoothChatService.STATE_LISTEN:

break;
case BluetoothChatService.STATE_NONE:
mTitle.setText(R.string.title_not_connected);
28
break;
}
break;
case MESSAGE_WRITE:
byte[] writeBuf = (byte[]) msg.obj;
// construct a string from the buffer
String writeMessage = new String(writeBuf);
mConversationArrayAdapter.add("Me: " + writeMessage);
break;
case MESSAGE_READ:
byte[] readBuf = (byte[]) msg.obj;
// construct a string from the valid bytes in the buffer
String readMessage = new String(readBuf, 0, msg.arg1);
mConversationArrayAdapter.add(mConnectedDeviceName+": " +
readMessage);
break;
case MESSAGE_DEVICE_NAME:
// save the connected device's name
mConnectedDeviceName = msg.getData().getString(DEVICE_NAME);
Toast.makeText(getApplicationContext(), "Connected to "
+ mConnectedDeviceName, Toast.LENGTH_SHORT).show();
break;
case MESSAGE_TOAST:
Toast.makeText(getApplicationContext(),
msg.getData().getString(TOAST),
Toast.LENGTH_SHORT).show();
break;
}
}
};

public void onActivityResult(int requestCode, int resultCode, Intent data) {
if(D) Log.d(TAG, "onActivityResult " + resultCode);
switch (requestCode) {
case REQUEST_CONNECT_DEVICE:
// When DeviceListActivity returns with a device to connect
if (resultCode == Activity.RESULT_OK) {
// Get the device MAC address
String address = data.getExtras()

.getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
// Get the BLuetoothDevice object
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
// Attempt to connect to the device
mChatService.connect(device);
}
break;
case REQUEST_ENABLE_BT:
// When the request to enable Bluetooth returns
if (resultCode == Activity.RESULT_OK) {
// Bluetooth is now enabled, so set up a chat session
setupChat();
} else {
// User did not enable Bluetooth or an error occured
Log.d(TAG, "BT not enabled");
29
Toast.makeText(this, R.string.bt_not_enabled_leaving,
Toast.LENGTH_SHORT).show();
finish();
}
}
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.scan:
// Launch the DeviceListActivity to see devices and do scan
Intent serverIntent = new Intent(this, DeviceListActivity.class);
startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
return true;
case R.id.discoverable:
// Ensure this device is discoverable by others
ensureDiscoverable();
return true;
}
return false;
}

}




BluetoothChatServices:

package com.example.bluetoothchat;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.os.Bundle;
30
import android.os.Handler;
import android.os.Message;
import android.util.Log;

/**
* This class does all the work for setting up and managing Bluetooth
* connections with other devices. It has a thread that listens for
* incoming connections, a thread for connecting with a device, and a
* thread for performing data transmissions when connected.
*/
public class BluetoothChatService {
// Debugging
private static final String TAG = "BluetoothChatService";
private static final boolean D = true;

// Name for the SDP record when creating server socket
private static final String NAME = "BluetoothChat";

// Unique UUID for this application
private static final UUID MY_UUID = UUID.fromString("fa87c0d0-afac-11de-8a39-
0800200c9a66");

// Member fields
private final BluetoothAdapter mAdapter;
private final Handler mHandler;
private AcceptThread mAcceptThread;
private ConnectThread mConnectThread;
private ConnectedThread mConnectedThread;
private int mState;

// Constants that indicate the current connection state
public static final int STATE_NONE = 0; // we're doing nothing
public static final int STATE_LISTEN = 1; // now listening for incoming
connections
public static final int STATE_CONNECTING = 2; // now initiating an outgoing
connection
public static final int STATE_CONNECTED = 3; // now connected to a remote device

/**
* Constructor. Prepares a new BluetoothChat session.
* @param context The UI Activity Context
* @param handler A Handler to send messages back to the UI Activity
*/
public BluetoothChatService(Context context, Handler handler) {
mAdapter = BluetoothAdapter.getDefaultAdapter();
mState = STATE_NONE;
mHandler = handler;
}

/**
* Set the current state of the chat connection
* @param state An integer defining the current connection state
*/
private synchronized void setState(int state) {
if (D) Log.d(TAG, "setState() " + mState + " -> " + state);
31
mState = state;

// Give the new state to the Handler so the UI Activity can update
mHandler.obtainMessage(BluetoothChat.MESSAGE_STATE_CHANGE, state, -
1).sendToTarget();
}

/**
* Return the current connection state. */
public synchronized int getState() {
return mState;
}

/**
* Start the chat service. Specifically start AcceptThread to begin a
* session in listening (server) mode. Called by the Activity onResume() */
public synchronized void start() {
if (D) Log.d(TAG, "start");

// Cancel any thread attempting to make a connection
if (mConnectThread != null) {mConnectThread.cancel(); mConnectThread = null;}

// Cancel any thread currently running a connection
if (mConnectedThread != null) {mConnectedThread.cancel(); mConnectedThread =
null;}

// Start the thread to listen on a BluetoothServerSocket
if (mAcceptThread == null) {
mAcceptThread = new AcceptThread();
mAcceptThread.start();
}
setState(STATE_LISTEN);
}

/**
* Start the ConnectThread to initiate a connection to a remote device.
* @param device The BluetoothDevice to connect
*/
public synchronized void connect(BluetoothDevice device) {
if (D) Log.d(TAG, "connect to: " + device);

// Cancel any thread attempting to make a connection
if (mState == STATE_CONNECTING) {
if (mConnectThread != null) {mConnectThread.cancel(); mConnectThread =
null;}
}

// Cancel any thread currently running a connection
if (mConnectedThread != null) {mConnectedThread.cancel(); mConnectedThread =
null;}

// Start the thread to connect with the given device
mConnectThread = new ConnectThread(device);
mConnectThread.start();
setState(STATE_CONNECTING);
32
}

/**
* Start the ConnectedThread to begin managing a Bluetooth connection
* @param socket The BluetoothSocket on which the connection was made
* @param device The BluetoothDevice that has been connected
*/
public synchronized void connected(BluetoothSocket socket, BluetoothDevice
device) {
if (D) Log.d(TAG, "connected");

// Cancel the thread that completed the connection
if (mConnectThread != null) {mConnectThread.cancel(); mConnectThread = null;}

// Cancel any thread currently running a connection
if (mConnectedThread != null) {mConnectedThread.cancel(); mConnectedThread =
null;}

// Cancel the accept thread because we only want to connect to one device
if (mAcceptThread != null) {mAcceptThread.cancel(); mAcceptThread = null;}

// Start the thread to manage the connection and perform transmissions
mConnectedThread = new ConnectedThread(socket);
mConnectedThread.start();

// Send the name of the connected device back to the UI Activity
Message msg = mHandler.obtainMessage(BluetoothChat.MESSAGE_DEVICE_NAME);
Bundle bundle = new Bundle();
bundle.putString(BluetoothChat.DEVICE_NAME, device.getName());
msg.setData(bundle);
mHandler.sendMessage(msg);

setState(STATE_CONNECTED);
}

/**
* Stop all threads
*/
public synchronized void stop() {
if (D) Log.d(TAG, "stop");
if (mConnectThread != null) {mConnectThread.cancel(); mConnectThread = null;}
if (mConnectedThread != null) {mConnectedThread.cancel(); mConnectedThread =
null;}
if (mAcceptThread != null) {mAcceptThread.cancel(); mAcceptThread = null;}
setState(STATE_NONE);
}

/**
* Write to the ConnectedThread in an unsynchronized manner
* @param out The bytes to write
* @see ConnectedThread#write(byte[])
*/
public void write(byte[] out) {
// Create temporary object
ConnectedThread r;
33
// Synchronize a copy of the ConnectedThread
synchronized (this) {
if (mState != STATE_CONNECTED) return;
r = mConnectedThread;
}
// Perform the write unsynchronized
r.write(out);
}

/**
* Indicate that the connection attempt failed and notify the UI Activity.
*/
private void connectionFailed() {
setState(STATE_LISTEN);

// Send a failure message back to the Activity
Message msg = mHandler.obtainMessage(BluetoothChat.MESSAGE_TOAST);
Bundle bundle = new Bundle();
bundle.putString(BluetoothChat.TOAST, "Unable to connect device");
msg.setData(bundle);
mHandler.sendMessage(msg);
}

/**
* Indicate that the connection was lost and notify the UI Activity.
*/
private void connectionLost() {
setState(STATE_LISTEN);

// Send a failure message back to the Activity
Message msg = mHandler.obtainMessage(BluetoothChat.MESSAGE_TOAST);
Bundle bundle = new Bundle();
bundle.putString(BluetoothChat.TOAST, "Device connection was lost");
msg.setData(bundle);
mHandler.sendMessage(msg);
}

/**
* This thread runs while listening for incoming connections. It behaves
* like a server-side client. It runs until a connection is accepted
* (or until cancelled).
*/
private class AcceptThread extends Thread {
// The local server socket
private final BluetoothServerSocket mmServerSocket;

public AcceptThread() {
BluetoothServerSocket tmp = null;

// Create a new listening server socket
try {
tmp = mAdapter.listenUsingRfcommWithServiceRecord(NAME, MY_UUID);
} catch (IOException e) {
Log.e(TAG, "listen() failed", e);
}
34
mmServerSocket = tmp;
}

public void run() {
if (D) Log.d(TAG, "BEGIN mAcceptThread" + this);
setName("AcceptThread");
BluetoothSocket socket = null;

// Listen to the server socket if we're not connected
while (mState != STATE_CONNECTED) {
try {
// This is a blocking call and will only return on a
// successful connection or an exception
socket = mmServerSocket.accept();
} catch (IOException e) {
Log.e(TAG, "accept() failed", e);
break;
}

// If a connection was accepted
if (socket != null) {
synchronized (BluetoothChatService.this) {
switch (mState) {
case STATE_LISTEN:
case STATE_CONNECTING:
// Situation normal. Start the connected thread.
connected(socket, socket.getRemoteDevice());
break;
case STATE_NONE:
case STATE_CONNECTED:
// Either not ready or already connected. Terminate new
socket.
try {
socket.close();
} catch (IOException e) {
Log.e(TAG, "Could not close unwanted socket", e);
}
break;
}
}
}
}
if (D) Log.i(TAG, "END mAcceptThread");
}

public void cancel() {
if (D) Log.d(TAG, "cancel " + this);
try {
mmServerSocket.close();
} catch (IOException e) {
Log.e(TAG, "close() of server failed", e);
}
}
}

35

/**
* This thread runs while attempting to make an outgoing connection
* with a device. It runs straight through; the connection either
* succeeds or fails.
*/
private class ConnectThread extends Thread {
private final BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;

public ConnectThread(BluetoothDevice device) {
mmDevice = device;
BluetoothSocket tmp = null;

// Get a BluetoothSocket for a connection with the
// given BluetoothDevice
try {
tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) {
Log.e(TAG, "create() failed", e);
}
mmSocket = tmp;
}

public void run() {
Log.i(TAG, "BEGIN mConnectThread");
setName("ConnectThread");

// Always cancel discovery because it will slow down a connection
mAdapter.cancelDiscovery();

// Make a connection to the BluetoothSocket
try {
// This is a blocking call and will only return on a
// successful connection or an exception
mmSocket.connect();
} catch (IOException e) {
connectionFailed();
// Close the socket
try {
mmSocket.close();
} catch (IOException e2) {
Log.e(TAG, "unable to close() socket during connection failure",
e2);
}
// Start the service over to restart listening mode
BluetoothChatService.this.start();
return;
}

// Reset the ConnectThread because we're done
synchronized (BluetoothChatService.this) {
mConnectThread = null;
}

36
// Start the connected thread
connected(mmSocket, mmDevice);
}

public void cancel() {
try {
mmSocket.close();
} catch (IOException e) {
Log.e(TAG, "close() of connect socket failed", e);
}
}
}

/**
* This thread runs during a connection with a remote device.
* It handles all incoming and outgoing transmissions.
*/
private class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;

public ConnectedThread(BluetoothSocket socket) {
Log.d(TAG, "create ConnectedThread");
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;

// Get the BluetoothSocket input and output streams
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) {
Log.e(TAG, "temp sockets not created", e);
}

mmInStream = tmpIn;
mmOutStream = tmpOut;
}

public void run() {
Log.i(TAG, "BEGIN mConnectedThread");
byte[] buffer = new byte[1024];
int bytes;

// Keep listening to the InputStream while connected
while (true) {
try {
// Read from the InputStream
bytes = mmInStream.read(buffer);

// Send the obtained bytes to the UI Activity
mHandler.obtainMessage(BluetoothChat.MESSAGE_READ, bytes, -1,
buffer)
.sendToTarget();
37
} catch (IOException e) {
Log.e(TAG, "disconnected", e);
connectionLost();
break;
}
}
}

/**
* Write to the connected OutStream.
* @param buffer The bytes to write
*/
public void write(byte[] buffer) {
try {
mmOutStream.write(buffer);

// Share the sent message back to the UI Activity
mHandler.obtainMessage(BluetoothChat.MESSAGE_WRITE, -1, -1, buffer)
.sendToTarget();
} catch (IOException e) {
Log.e(TAG, "Exception during write", e);
}
}

public void cancel() {
try {
mmSocket.close();
} catch (IOException e) {
Log.e(TAG, "close() of connect socket failed", e);
}
}
}
}


DeviceListActivity:

package com.example.bluetoothchat;

import java.util.Set;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
38
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

/**
* This Activity appears as a dialog. It lists any paired devices and
* devices detected in the area after discovery. When a device is chosen
* by the user, the MAC address of the device is sent back to the parent
* Activity in the result Intent.
*/
public class DeviceListActivity extends Activity {
// Debugging
private static final String TAG = "DeviceListActivity";
private static final boolean D = true;

// Return Intent extra
public static String EXTRA_DEVICE_ADDRESS = "device_address";

// Member fields
private BluetoothAdapter mBtAdapter;
private ArrayAdapter<String> mPairedDevicesArrayAdapter;
private ArrayAdapter<String> mNewDevicesArrayAdapter;

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

// Setup the window
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.device_list);

// Set result CANCELED incase the user backs out
setResult(Activity.RESULT_CANCELED);

// Initialize the button to perform device discovery
Button scanButton = (Button) findViewById(R.id.button_scan);
scanButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
doDiscovery();
v.setVisibility(View.GONE);
}
});

// Initialize array adapters. One for already paired devices and
// one for newly discovered devices
mPairedDevicesArrayAdapter = new ArrayAdapter<String>(this,
R.layout.device_name);
mNewDevicesArrayAdapter = new ArrayAdapter<String>(this,
R.layout.device_name);

// Find and set up the ListView for paired devices
ListView pairedListView = (ListView) findViewById(R.id.paired_devices);
39
pairedListView.setAdapter(mPairedDevicesArrayAdapter);
pairedListView.setOnItemClickListener(mDeviceClickListener);

// Find and set up the ListView for newly discovered devices
ListView newDevicesListView = (ListView) findViewById(R.id.new_devices);
newDevicesListView.setAdapter(mNewDevicesArrayAdapter);
newDevicesListView.setOnItemClickListener(mDeviceClickListener);

// Register for broadcasts when a device is discovered
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
this.registerReceiver(mReceiver, filter);

// Register for broadcasts when discovery has finished
filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
this.registerReceiver(mReceiver, filter);

// Get the local Bluetooth adapter
mBtAdapter = BluetoothAdapter.getDefaultAdapter();

// Get a set of currently paired devices
Set<BluetoothDevice> pairedDevices = mBtAdapter.getBondedDevices();

// If there are paired devices, add each one to the ArrayAdapter
if (pairedDevices.size() > 0) {
findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE);
for (BluetoothDevice device : pairedDevices) {
mPairedDevicesArrayAdapter.add(device.getName() + "\n" +
device.getAddress());
}
} else {
String noDevices =
getResources().getText(R.string.none_paired).toString();
mPairedDevicesArrayAdapter.add(noDevices);
}
}

@Override
protected void onDestroy() {
super.onDestroy();

// Make sure we're not doing discovery anymore
if (mBtAdapter != null) {
mBtAdapter.cancelDiscovery();
}

// Unregister broadcast listeners
this.unregisterReceiver(mReceiver);
}

/**
* Start device discover with the BluetoothAdapter
*/
private void doDiscovery() {
if (D) Log.d(TAG, "doDiscovery()");

40
// Indicate scanning in the title
setProgressBarIndeterminateVisibility(true);
setTitle(R.string.scanning);

// Turn on sub-title for new devices
findViewById(R.id.title_new_devices).setVisibility(View.VISIBLE);

// If we're already discovering, stop it
if (mBtAdapter.isDiscovering()) {
mBtAdapter.cancelDiscovery();
}

// Request discover from BluetoothAdapter
mBtAdapter.startDiscovery();
}

// The on-click listener for all devices in the ListViews
private OnItemClickListener mDeviceClickListener = new OnItemClickListener() {
public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3) {
// Cancel discovery because it's costly and we're about to connect
mBtAdapter.cancelDiscovery();

// Get the device MAC address, which is the last 17 chars in the View
String info = ((TextView) v).getText().toString();
String address = info.substring(info.length() - 17);

// Create the result Intent and include the MAC address
Intent intent = new Intent();
intent.putExtra(EXTRA_DEVICE_ADDRESS, address);

// Set result and finish this Activity
setResult(Activity.RESULT_OK, intent);
finish();
}
};

// The BroadcastReceiver that listens for discovered devices and
// changes the title when discovery is finished
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();

// When discovery finds a device
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice device =
intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// If it's already paired, skip it, because it's been listed already
if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
mNewDevicesArrayAdapter.add(device.getName() + "\n" +
device.getAddress());
}
// When discovery is finished, change the Activity title
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
41
setProgressBarIndeterminateVisibility(false);
setTitle(R.string.select_device);
if (mNewDevicesArrayAdapter.getCount() == 0) {
String noDevices =
getResources().getText(R.string.none_found).toString();
mNewDevicesArrayAdapter.add(noDevices);
}
}
}
};

}

Actionbar.java:-
package com.markupartist.android.widget;
import java.util.LinkedList;
import com.markupartist.android.widget.actionbar.R;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class ActionBar extends RelativeLayout implements OnClickListener {

private LayoutInflater mInflater;
42
private RelativeLayout mBarView;
private ImageView mLogoView;
private View mBackIndicator;
//private View mHomeView;
private TextView mTitleView;
private LinearLayout mActionsView;
private ImageButton mHomeBtn;
private RelativeLayout mHomeLayout;
private ProgressBar mProgress;

public ActionBar(Context context, AttributeSet attrs) {
super(context, attrs);

mInflater = (LayoutInflater)
context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

mBarView = (RelativeLayout) mInflater.inflate(R.layout.actionbar, null);
addView(mBarView);

mLogoView = (ImageView) mBarView.findViewById(R.id.actionbar_home_logo);
mHomeLayout = (RelativeLayout) mBarView.findViewById(R.id.actionbar_home_bg);
mHomeBtn = (ImageButton) mBarView.findViewById(R.id.actionbar_home_btn);
mBackIndicator = mBarView.findViewById(R.id.actionbar_home_is_back);

mTitleView = (TextView) mBarView.findViewById(R.id.actionbar_title);
mActionsView = (LinearLayout) mBarView.findViewById(R.id.actionbar_actions);

mProgress = (ProgressBar) mBarView.findViewById(R.id.actionbar_progress);

TypedArray a = context.obtainStyledAttributes(attrs,
R.styleable.ActionBar);
CharSequence title = a.getString(R.styleable.ActionBar_title);
43
if (title != null) {
setTitle(title);
}
a.recycle();
}

public void setHomeAction(Action action) {
mHomeBtn.setOnClickListener(this);
mHomeBtn.setTag(action);
mHomeBtn.setImageResource(action.getDrawable());
mHomeLayout.setVisibility(View.VISIBLE);
}

public void clearHomeAction() {
mHomeLayout.setVisibility(View.GONE);
}

/**
* Shows the provided logo to the left in the action bar.
*
* This is ment to be used instead of the setHomeAction and does not draw
* a divider to the left of the provided logo.
*
* @param resId The drawable resource id
*/
public void setHomeLogo(int resId) {
// TODO: Add possibility to add an IntentAction as well.
mLogoView.setImageResource(resId);
mLogoView.setVisibility(View.VISIBLE);
mHomeLayout.setVisibility(View.GONE);
}

44
/* Emulating Honeycomb, setdisplayHomeAsUpEnabled takes a boolean
* and toggles whether the "home" view should have a little triangle
* indicating "up" */
public void setDisplayHomeAsUpEnabled(boolean show) {
mBackIndicator.setVisibility(show? View.VISIBLE : View.GONE);
}


public void setTitle(CharSequence title) {
mTitleView.setText(title);
}

public void setTitle(int resid) {
mTitleView.setText(resid);
}

/**
* Set the enabled state of the progress bar.
*
* @param One of {@link View#VISIBLE}, {@link View#INVISIBLE},
* or {@link View#GONE}.
*/
public void setProgressBarVisibility(int visibility) {
mProgress.setVisibility(visibility);
}

/**
* Returns the visibility status for the progress bar.
*
* @param One of {@link View#VISIBLE}, {@link View#INVISIBLE},
* or {@link View#GONE}.
*/
45
public int getProgressBarVisibility() {
return mProgress.getVisibility();
}

/**
* Function to set a click listener for Title TextView
*
* @param listener the onClickListener
*/
public void setOnTitleClickListener(OnClickListener listener) {
mTitleView.setOnClickListener(listener);
}

@Override
public void onClick(View view) {
final Object tag = view.getTag();
if (tag instanceof Action) {
final Action action = (Action) tag;
action.performAction(view);
}
}

/**
* Adds a list of {@link Action}s.
* @param actionList the actions to add
*/
public void addActions(ActionList actionList) {
int actions = actionList.size();
for (int i = 0; i < actions; i++) {
addAction(actionList.get(i));
}
}
46

/**
* Adds a new {@link Action}.
* @param action the action to add
*/
public void addAction(Action action) {
final int index = mActionsView.getChildCount();
addAction(action, index);
}

/**
* Adds a new {@link Action} at the specified index.
* @param action the action to add
* @param index the position at which to add the action
*/
public void addAction(Action action, int index) {
mActionsView.addView(inflateAction(action), index);
}

/**
* Removes all action views from this action bar
*/
public void removeAllActions() {
mActionsView.removeAllViews();
}

/**
* Remove a action from the action bar.
* @param index position of action to remove
*/
public void removeActionAt(int index) {
mActionsView.removeViewAt(index);
47
}

/**
* Remove a action from the action bar.
* @param action The action to remove
*/
public void removeAction(Action action) {
int childCount = mActionsView.getChildCount();
for (int i = 0; i < childCount; i++) {
View view = mActionsView.getChildAt(i);
if (view != null) {
final Object tag = view.getTag();
if (tag instanceof Action && tag.equals(action)) {
mActionsView.removeView(view);
}
}
}
}

/**
* Returns the number of actions currently registered with the action bar.
* @return action count
*/
public int getActionCount() {
return mActionsView.getChildCount();
}

/**
* Inflates a {@link View} with the given {@link Action}.
* @param action the action to inflate
* @return a view
*/
48
private View inflateAction(Action action) {
View view = mInflater.inflate(R.layout.actionbar_item, mActionsView, false);

ImageButton labelView =
(ImageButton) view.findViewById(R.id.actionbar_item);
labelView.setImageResource(action.getDrawable());

view.setTag(action);
view.setOnClickListener(this);
return view;
}

/**
* A {@link LinkedList} that holds a list of {@link Action}s.
*/
public static class ActionList extends LinkedList<Action> {
}

/**
* Definition of an action that could be performed, along with a icon to
* show.
*/
public interface Action {
public int getDrawable();
public void performAction(View view);
}

public static abstract class AbstractAction implements Action {
final private int mDrawable;

public AbstractAction(int drawable) {
mDrawable = drawable;
49
}

@Override
public int getDrawable() {
return mDrawable;
}
}

public static class IntentAction extends AbstractAction {
private Context mContext;
private Intent mIntent;

public IntentAction(Context context, Intent intent, int drawable) {
super(drawable);
mContext = context;
mIntent = intent;
}

@Override
public void performAction(View view) {
try {
mContext.startActivity(mIntent);
} catch (ActivityNotFoundException e) {
Toast.makeText(mContext,
mContext.getText(R.string.actionbar_activity_not_found),
Toast.LENGTH_SHORT).show();
}
}
}

/*
public static abstract class SearchAction extends AbstractAction {
50
public SearchAction() {
super(R.drawable.actionbar_search);
}
}
*/
}















XML Layouts:
Activity_main:-
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<ListView
android:id="@+id/in"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:stackFromBottom="true"
android:transcriptMode="alwaysScroll" />

51
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >

<EditText
android:id="@+id/edit_text_out"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:layout_weight="1" />

<Button
android:id="@+id/button_send"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/send" />
</LinearLayout>

<TextView
android:id="@+id/title_left_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/title_right_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />

</LinearLayout>




devicelist_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView android:id="@+id/title_paired_devices"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="title_paired_devices"
android:visibility="gone"
android:background="#666"
android:textColor="#fff"
android:paddingLeft="5dp"
/>
<ListView android:id="@+id/paired_devices"
52
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:stackFromBottom="true"
android:layout_weight="1"
/>
<TextView android:id="@+id/title_new_devices"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="title_other_devices"
android:visibility="gone"
android:background="#666"
android:textColor="#fff"
android:paddingLeft="5dp"
/>
<ListView android:id="@+id/new_devices"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:stackFromBottom="true"
android:layout_weight="2"
/>
<Button android:id="@+id/button_scan"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="button_scan"
/>
</LinearLayout>

Message.xml:-
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="18sp"
android:padding="5dp"
/>

Devicename.xml:-
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="18sp"
android:padding="5dp"
/>
Actionbar.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/screen"
android:layout_width="fill_parent"
android:layout_height="@dimen/actionbar_height"
53
android:orientation="horizontal"
>
<RelativeLayout
android:id="@+id/actionbar_home"
android:layout_width="wrap_content"
android:layout_height="@dimen/actionbar_height"
android:orientation="horizontal"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:visibility="visible"
>
<ImageView
android:id="@+id/actionbar_home_logo"
android:layout_width="wrap_content"
android:layout_height="@dimen/actionbar_height"
android:background="@drawable/actionbar_btn"
android:padding="0dip"
style="@style/ActionBarHomeLogo"
android:visibility="gone"
/>
<RelativeLayout
android:id="@+id/actionbar_home_bg"
android:layout_width="wrap_content"
android:layout_height="@dimen/actionbar_height"
android:orientation="horizontal"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:background="@color/actionbar_separator"
android:visibility="gone"
>
<!-- TODO: Make configurable. -->
<ImageButton
android:id="@+id/actionbar_home_btn"
style="@style/ActionBarHomeItem"
android:background="@drawable/actionbar_btn"
/>
</RelativeLayout>
<ImageView
android:id="@+id/actionbar_home_is_back"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/actionbar_back_indicator"

android:layout_alignParentTop="true"
android:padding="0dip"
android:visibility="gone"
/>

<LinearLayout
android:orientation="horizontal"
android:id="@+id/actionbar_actions"
android:layout_width="wrap_content"
android:layout_height="@dimen/actionbar_height"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
54
android:layout_margin="0dp"
android:padding="0dp"
android:background="@color/actionbar_separator"
/>

<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/actionbar_home_bg"
android:layout_toLeftOf="@id/actionbar_actions"
android:layout_alignWithParentIfMissing="true"
android:layout_centerVertical="true"
>
<ProgressBar
android:id="@+id/actionbar_progress"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:paddingRight="7dip"
android:indeterminateOnly="true"
android:visibility="gone"
style="@style/ActionBarProgressBar"
/>
<com.markupartist.android.widget.ScrollingTextView
android:id="@+id/actionbar_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_toLeftOf="@id/actionbar_progress"
android:paddingLeft="10dip"
android:paddingRight="10dip"
android:textSize="16dip"
android:textStyle="bold"
android:textColor="@color/actionbar_title"
android:lines="1"
android:scrollHorizontally="true"
android:ellipsize="marquee"
android:marqueeRepeatLimit="marquee_forever"
/>
</RelativeLayout>
</RelativeLayout>
</RelativeLayout>






55
8. TESTING

TECHNICAL TOOLS:-
ARM architecture:
ARM is a family of instruction set architectures for computer processors based on a reduced
instruction set computing (RISC) architecture developed by British company ARM Holdings.
A RISC-based computer design approach means ARM processors require significantly fewer
transistors than typical processors in average computers. This approach reduces costs, heat and
power use. These are desirable traits for light, portable, battery-powered devicesincluding
smartphones, laptops, tablet and notepad computers, and other embedded systems. A simpler
design facilitates more efficient multi-core CPUs and higher core counts at lower cost, providing
higher processing power and improved energy efficiency for servers and supercomputers.ARM
Holdings develops the instruction set and architecture for ARM-based products, but does not
manufacture products. The company periodically releases updates to its cores. Current cores
from ARM Holdings support a 32-bit address space and 32-bit arithmetic; the recently
introduced ARMv8-A architecture adds support for a 64-bit address space and 64-bit arithmetic.
Instructions for ARM Holdings' cores have 32-bit-wide fixed-length instructions, but later
versions of the architecture also support a variable-length instruction set that provides both 32-bit
and 16-bit-wide instructions for improved code density. Some cores can also provide hardware
execution of Java bytecodes.
Testing Log









56
9.CONCLUSION
Add/Remove quick texts
Speak to text
Play sound upon message arrival
Vibrate upon message arrival
Transfer images as well as transfer files or data
Also share data on different on-line services.

















57
10. FUTURE SCOPE
Different type of fonts can be used.
Used in a small group to share messages, images and files.
Attractive graphic features.
Other mobile operating system can be used than Android.



















58
11.BIBLIOGRAPHY

1. www.Betasoftsystem.com
2. msdn.mircosoft.com
3. Google my.safaribooksonline.com,codeproject.com etc
4. Daily Dairy
5. JAVATPOINT Android

You might also like