Sie sind auf Seite 1von 4

Research and design of chatting room system based

on Android Bluetooth
S Anand anand.sampath03@gmail.com9840673610
Giri Tungala tungalagiri@gmail.com8015634709
Mohd Abdul Latif mohdabdullatif10@gmail.com9962334691
VeltechMultitechDr RangarajanDr SakunthalaEngineeringCollege
Departmentof InformationTechnology
AbstractBluetooth provides a low-power and low-cost wireless
connection among mobile devices and their accessories, which is
an op en standard for implementing a short-range wireless
communication. Bluetooth is integrated into Android which is a
mainstream smart phone platform as a mean of mobile
communication. Android has attracted a large number of
developers because of its character of open sourcing and powerful
application API. This article takes designing a Bluetooth chat
room for example to research Bluetooth and its architecture of
android platform and introduce the process of realizing the
Bluetooth communication in detail. Then we design and
implement a chat roombased on Bluetooth by using APIs of
Android platform. At last, a further prospect of the function of
this system was made.
Keywords - component; Android; Bluetooth; wireless
communication; chat room
I. INTRODUCTION
In recent years, with the development of mobile
communication and Mobileterminal, especially the releaseof
Android smart phone platformhas injected newvitality to the
mobile space. Android is a open sourcing mobile operating
system based o n Linux which is a Completely open and
integrated platform for mobile devices. Android platform
consists of the operating system, middleware, user interface and
application software[I]. Bluetoothtechnology is amatureshort-
range wireless communication technology. The working
frequency band of Bluetooth do not needalicense aroundthe
globe. Theadvantageof Bluetooth technology arereflected in
the low price, easy to control and non-visual distance
limitations. Bluetooth is an important feature of the smart
phone, which is integrated into the Android platform, as the
Androidmobile networkcommunication module. TheAndroid
systemprovidesmanyBluetoothAPIsfor developerstocall.
The majority of thephonecommunicatewitheachat her
generallythroughChina Mobileor China Unicom gateway,
whichhavetopay relatedcosts. Thepurposeof thechat room
whichbasedtheBluetoothof androidisconnectphonesintoa
local areanetwork, thenwe cancommunicatewitheach other
without any cost. Thispaper carry out achat systemviathe
API of theBluetooth ontheAndroid platform. Through the
Bluetooth module, androidphonescanbe dividedintoclient
andserver andthenthereal-timechatbetweenfriends or
strangerscanbeaccomplished.
II. BLUETOOTHANDBLUETOOTH ARCHITECTURE
Bluetooth technology is wireless net working technology;
thepurposeof it istoprovideashort-range, low-cost wireless
transmissiontechnology for handheld devices andavariety of
consumer electronicproducts. Bluetootharchitectureincluding
hardwaremodules and t he middlelayer underlying protocol
layerswell high-level applications [2].
AndroidBluetoothsystemcontains Bluetooth driver, Linux
kernel, Bluetoothprotocol layersblueZBluetoothuser library,
blueZ adaptation layer. T heandroid.bluetooth class package,
Bluetooth applications. The part of Android Bluetooth
structure hasbeenshowninFigureI:
FigureI. thestructureof androidBluetooth
Bluetooth cantransmissionasynchronousdataand
Synchronous languages at the same time, its underlying
protocol layer includea number of agreements. Such as L2C
AP, SDP, RFCOMM and so on, which toprovidesupport for
t he upper transmission. The relationship between Bluetooth
protocol has showninFigure2:
Figure2. TherelationshipbetweenBluetoothprotocol
III. DESIGNOFANDROID BLUETOOTH COMMUNICATION
This paper is to use the Bluetooth API providedbythe
Androidplatformtoimplement communicationbetweenBlue-
tooth devices. Bluetooth communicationi sbased on unique
MAC. Takingintoaccount thesecurityissues, theBluetooth
devicemustbeenpairedbeforeusingBluetoothcommunication.
Theconnecteddeviceswill beshared withaRFCOMM channel
totransmit data. Therefore, theprocessof Bluetooth
communicationincludesthreesteps:
I) Query Bluetooth, wecan useBluetooth Adapter to get
theBluetoothActivityandthemethodof onActivityResult() toget
the Bluetooth connection intent. Figure3 shows t he query
pairingprocess. Figure3showsthequerypairingprocess.
2) FindingDevices, we need to opentheBluetooth user
nameandMACaddresstopair theBluetooth.
3) Connecting Bluetooth. Figure 4 shows the process of
pairing connection. Bluetooth communication to achieve t he
following. Following is the detailed design of the Bluetooth
communication.
Figure3. Bluetoothinquiries, thepairingprocess
Figure4. Bluetoothpairing and connectionprocess
A. Findding / Discovering Devices
Howt ofindtheAndroidBluetoothdev ices? Thisarticle
usesthemethodof start Discovery() int theclassBluetooth
Adapter toexecuteanasynchronousway t oget aroundthe
Bluetoothdevice, Becauseitisanasynchronousmethodso we
do not needtoconsider thethreadi s blocked. The whole
processtakes about 12seconds[3]. Thenweregister a
BroadcastReceiver objecttoreceivethe Bluetoothde vice
information. Wefilter ACTION FOUNDIntent actionto
obtainedtailedinformationfor eachremotedevice. Additional
parametersintheIntent fieldEXTRA DEVICE anEXT RA
CLASS, whichcontainsthedevicetype of the object andthe
object of BluetoothDevice. Samplecodeisasfollows:
Privatefinal BroadcastReceiver Receiver=newBroadcastReceiver() {
publicvoidonReceive(Context context, Intentintent) {
Stringaction=intent.getAction();
if (BluetoothDevice.ACTION FOUND.equals(action)) {
BluetoothDevicedevice=
intent.getParcelableExtra(BluetoothDevice.EXTRA DEVICE);
myArrayAdapter.add(device.getName() +" nameI " +device.ge
tAddress()); //Toobtainthedevicenameandmacaddress
}}};
B. PairedDevice
Pairinga Bluetoothdevi ce we can call the method of
getBondedDevices() intheclassBluetoothAdapter toobtaina
paireddevice. Themethod will return Bluetoothdevicearray
todistinguishbetweeneachpaired device, samplecodeisas
follows:
SetpairedDevices=cwjBluetoothAdapter.getBondedDevices();
/ / If theresultisgreater than0, thenbegantoresolveonebyone
if (pairedDevices.size() >0){
for (BluetoothDevicedevice: pairedDevices) {
/ /GetthenameandMACaddressof eachdevice
myArrayAdapter.add(device.getName() +" nameI " +device.get
Address()); }}
C. Establishing
For theestablishment of aBluetooth communicationmust
gothroughthefollowingfour steps: get local Bluetooth devices
,find theremote device, pairing, connect devices andtransfer
data.
IntheAndroidplatform, first of all, w eneedtofin d a
Bluetooth adapter for local activities, through the method
getDefaultAdapter () in the class Bluetooth Adapter to obtain
thesystemdefault Bluetoothdevice. Samplecodeisasfollows:
BluetoothAdapter cwjBluetoothAdapter
=BluetoothAdapter.getDefaultAdapter();
if (cwjBluetoothAdapter ==null) {
}
Of coursewiththis stepwecannot establishaconnection,
becausewedonot knowthephoneBluetoothfunctionisturned
on, wecanusethemethodof IsEnabledinCwjBluetoothAdapter
todeterminewhether to op entheBluetooth, if not open, we
canusethefollowingcodetoenablefunction.
if (!cwjBluetoothAdapter.isEnabled()) {
Intent TurnOnBtIntent =new
Intent(BluetoothAdapter.ACTION REQUEST ENABLE);
startActivityForResult(TurnOnBtIntent, REQUEST ENABLE BT);
}
Intent will be initiatedby startActivityForResult () method
in the onActivityResult () call back method to obtain the
user's choice. Suchasthe user clicksYesto open,
it will receive RESULT OK , The RESULT CANCELED on
behalf of the users are unwilling to turn on Bluetooth, Of
course, there are many ways to open the Bluetooth service
interface. For instance, weuse theBluetoothDevice to access
theBluetoothservice interfaceobject. Whenweusethe enable
() methodtoopen, without askingtheuser, thenyouneed touse
thepermissionof android.permission.BLUETOOTH.
Howtojudget hestatusof thesystemBluetooth?
Establishment of broadcast receiver, receiveACTION STATE
CHANGED action. IntheEXTRA STATE andEXTRA PRE
VIOUSSTATE contains thepresent stateand past state. The
final resultsisdefinedas: theSTATE TURNING ON
representativesopening, the STATE ONrepresentativeshave
beenopen, TheSTATE TURNING OFF isclosingand STATE
OF representativehasbeenclosed.
D. THEOVERALL DESIGNOFTHEANDROIDBLUETOOTH
CHAT ROOM
Bluetooth communication, similar to TCP traffic, we need
to havet heserver andclient. In this chat system, an Android
phoneasaBluetoothserver-side, theother Androidphoneasa
Bluetooth client. Client connected to the server and receives
messagetxt from server, alsosendmessagetext totheser ver.
Theserver alsoabletosendandreceivetextmessages.
Thissystemmainlyused theAndroidsystemcomponents
istheActivityandService. IntheAndroidsystemeach Activity
is anindependentprocess, eachServiceisan independent
process, whiletheActivityandServicemust be
communicatewitheachother, then you needto usetheBinder
mechanism[4].AndroidBinder mechanismabstract definedby
Binder interface. In the upper, its concrete implementation is
completeby AIDL.T hemain programof this system include
three files: BluetoothChat.java BluetoothChatService.java and
DeviceListActivity.java, detailed features can be seen below
thedescriptionshowninFigure5:
Figure5, the systemas call sequencediagram
IV. THEDETAILEDDESIGNOF THE ANDROIDBLUETOOTH
CHAT ROOM
A. Server Design
Whenyouwanttoconnect twodevices, onemustasa
server (byholdingan open bluetoothserversocket), whichi s
designedtolistenfor incomingconnectionsrequests. Whenthe
clientget Bluetooth socket fromBluetooth server socketcanto
beendestructed, unlessyouwant tolistenfor moreconnection
requests. Establish theservicesocket and listeningfor
connections, thebasicstepsareasfollows:
1) Wecancall listenUsingRfcommWithServiceRecord
(String,UUID) toget Bluetoothserversocket. Theparameter
stringrepresentsthenameof theservice, UUIDrepresentsa
sign of the connection (I D isastringof I28,equivalent to the
pincode).UUIDmust matcheachother after connected..
2) Wecall themethod of accept() to listenfor theconnec-
tionrequeststhat maycome, whenwelistenarequest , returna
connectiononBluetoothsocket bluetoothsocket.
3) Weneedcall close() after listeningtoaconnectionto
closethelistener(Generally thetransmissionispoint-to-point
between Bluetoothdevices).
B. Client design
In order to initializeaconnectiontotheremote device, you
need toget a Bluetooth deviceobject. Wetoobtainbluetooth
socket and initialize the connection by the bluetoothdevice
object .thespecificsteps.
We use t he method of RfcommSocketToServiceRecode
(UUID) i ntheBluetoothdevicetoget theBluetoothsocket.
Then, callingconnect() method. If theremotedevicetoreceive
the connection, they will share RFCOMM channel in the
communicationprocess.
connect() method is blocking call , and generally createa
separate thread to call t he method. When the device i s
connecting should not be initiated connect the method o f
connect(),this will obviously slow downsothat theconnection
fails. Once data transfer is completely, only call the close()
method to close the connection. This can save the sytem
internal resources.
C. Management Connections
1) First call themethodof getInputStream() and getOutput
Stream() method to obtaintheinput and output streams, then
call the method of read (byte[]) andwrite(byte[]) t o read or
writedata.
2) Implementationdetails: Theread and writeoperation are
blocking calls that need to establish a dedicated to manage.
privateclassConnectedThreadextendsThread{
privatefinal BluetoothSocketmmSocket;
privatefinal InputStreammmInStream;
privatefinal OutputStreammmOutStream;
publicConnectedThread(BluetoothSocket socket) {
mmSocket =socket;
InputStreamtmpIn=null;
OutputStreamtmpOut =null;
// Gettheinputandoutput streams, usingtempobjectsbecause
// member streamsarefinal
try {
tmpIn=socket.getInputStream();
tmpOut=socket.getOutputStream();
}catch(IOExceptione) {}
mmInStream=tmpIn;
mmOutStream=tmpOut;
}
publicvoidrun() {
byte[] buffer =new byte[I024]; // buffer storefor the stream
int bytes; // bytesreturnedfromread()
// KeeplisteningtotheInputStreamuntil anexceptionoccurs
while(true) {
try {
// ReadfromtheInputStream
bytes=mmInStream.read(buffer);
// SendtheobtainedbytestotheUI Activity
mHandler.obtainMessage(MESSAGE READ, bytes, -I, buffer)
.sendToTarget();
}catch(IOExceptione) {
break;
}}}
/* Call thisfromthemainActivitytosenddatatotheremotedevice*/
publicvoidwrite(byte[] bytes) {
try {
mmOutStream.write(bytes);
}catch(IOExceptione) {}
}
/* Call thisfromthemainActivitytoshutdowntheconnection*/
publicvoidcancel() {
try {
mmSocket.close();
}catch(IOExceptione) {}
}}
V. SUMMARY ANDPROSPEC
TheInternetageof today, chatroomisof agreatentertainment
features project, muchof theInternetusersarelikeit. Design
andrealizationof chattingroomsystembasedon Android
Bluetoothisgoodfor developingBluetoothnetwork
applicationandBluetoothagreement. Thesystemhave
realizedthebroadcast andprivatechat betweenmobilephones.
But Richer input format, theexpressionof information, picture,
information, pictures, information transmission, still need to
further improvetheusability and functionalityof the system.
REFERENCES
[I] E2ECloud studio. Google Android[M] Posts & TelecomPress. 2009
[2] TheBluetoothSpecial I nterest Group.Bluetooth SpecificationCorev4.0.
(2009-02).Http://www.bluetooth.org.
[3] HanChao, LiangQuan, principles anddevelopmentpointsof theAndroid
system[M]. PublishingHouseof ElectronicsIndustry.20I0
[4] Yang Fengsheng. Android Inside[M]. Machinery Industry Press. 2008
[5] AndreNKlingsheim. J 2ME BluetoothProgramming[D]. Departmentof
InformaticsUniversityof bergen,2004

Das könnte Ihnen auch gefallen