blutooth chat project report

Upload: deven-rathore

Post on 28-Feb-2018

1.117 views

Category:

Documents


187 download

TRANSCRIPT

  • 7/25/2019 blutooth chat project report

    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

  • 7/25/2019 blutooth chat project report

    2/58

    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

  • 7/25/2019 blutooth chat project report

    3/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 toMrs. 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 thesuccessful completion of my synopsis report.

    Anil Kumar

  • 7/25/2019 blutooth chat project report

    4/58

    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

    mailto:[email protected]:[email protected]:[email protected]:[email protected]:[email protected]:[email protected]
  • 7/25/2019 blutooth chat project report

    5/58

    5

    3. COMPANY PROFILE (BETA SOFT SYSTEM)

    Establishment:

    Established in 2005, by Ritu and Vishal Mangla, Beta Soft SystemsInc 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 Systemsis 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 toour in-house talent.

    Beta Soft Systemsunwavering commitment to its clientsprofitability has been the crux of our 4P strategy. We focus on Product, Process, Portal andPublic Relations, the four corner stones of a successful modern day business. Depending on ourclients business model, we target the required function and build resource optimization andtalent management processes and bring about significant revenue impact for our clients.

    Beta Soft Systemshelps clients in building profitablebusiness models by leveraging on industry-wide experience, expertise from subject matterexperts, 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 toharness the latest technologies across Industries for delivering unmatched value.

  • 7/25/2019 blutooth chat project report

    6/58

    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 growthevery 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. Wehave 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/25/2019 blutooth chat project report

    7/58

    7

    4. PROJECT INTRODUCTION

    ABSTRACT:

    Bluetooth chatting is an innovative approach to the mobile world. This application shows use ofBluetooth in terms of chatting. Means persons can chat via Bluetooth. The main midlet has just alist which has two values server and client. By selecting one of these two values, thecorresponding instance is created. Midlet is used to initialize the connection. It does followingthing at here. First, it starts the application and search the Bluetooth device. It sends the signal tothe server class. Second, it can run, pause and stop the application. Third, it shows alert usingsetAlert function on every changing. Server class goes active when it go signal from the midletclass. It sends the hello world string with the string to the other devices. Client class works torespond the other Bluetooth device server.

    Royal Bluetooth chat is aBluetoothmessaging. Royal Bluetooth Chat allows you to see otherBluetooth Chat users around, ping anyone of them, and create eitherprivatechatsessions orpublic messaging rooms via Bluetooth. This application allows two Android devices to carry outtwo-way text chat over Bluetooth. Start the application from the first screen; splash Screeng andthan 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, selectSearch' option which attempts to discover other users in the area. Detected user-profiles arelisted as selectable boxes. While a profile is selected, Options menu can be used to view profiledetails, 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 devicesand see Bluetooth compatible devices around you. No GSM or Wi-Fi connection required allyou need is a two Bluetooth compatible android devices in range of each other and you can textaway. If you have internet connection you can also share messages, images and also files in onGmail, face-book and other compatible services. To chat with a user, select it from the list andpress Ping' to send a welcome message. The other user may do the same. As the welcomemessage is displayed, use right or left soft key to accept or reject the chat session. Once thesession is accepted, the chat starts with colorful text to differentiate users. In addition to thisperson-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 initialcommunicationand 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.

    http://mobile.brothersoft.com/download/bluetooth.htmlhttp://mobile.brothersoft.com/download/bluetooth.htmlhttp://mobile.brothersoft.com/download/bluetooth.htmlhttp://mobile.brothersoft.com/download/private.htmlhttp://mobile.brothersoft.com/download/private.htmlhttp://mobile.brothersoft.com/download/chat.htmlhttp://mobile.brothersoft.com/download/chat.htmlhttp://mobile.brothersoft.com/download/chat.htmlhttp://mobile.brothersoft.com/download/communication.htmlhttp://mobile.brothersoft.com/download/communication.htmlhttp://mobile.brothersoft.com/download/communication.htmlhttp://mobile.brothersoft.com/download/communication.htmlhttp://mobile.brothersoft.com/download/chat.htmlhttp://mobile.brothersoft.com/download/private.htmlhttp://mobile.brothersoft.com/download/bluetooth.html
  • 7/25/2019 blutooth chat project report

    8/58

    8

    Be aware that if more than one peer do "Look for friends" simultaneously, they might not beable 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 devicesThis application begins searching for devices as soon as it is opened. Options menuappear only after a successful or unsuccessful search is complete. Other options are newmessage alert - vibrate or sound, and refresh rate setting ranging from 30 seconds to threeminutes. Users can manually refresh the list of users as well. Select a user from the listand use Options.

    Querying the local Bluetooth adapter for paired Bluetooth devices

    TheBluetooth Adapteris the entry-point for all Bluetooth interaction. Using this, you candiscover other Bluetooth devices, query a list of bonded (paired) devices, instantiateaBluetooth Deviceusing a known MAC address, and create aBluetoothServerSockettolisten for communications from other devices. Use this to request a connection with aremote device through aBluetooth Socketor query information about the device such asits name, address, class, and bonding state. Represents the interface for a Bluetoothsocket (similar to a TCPSocket). This is the connection point that allows an applicationto 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 communicationchannel. Sockets are not connected when they are first created, and are useless until a callto either connect (client application) or accept (server application) completessuccessfully. Once a socket is connected, it can be used to send and receive data until theconnection fails due to link error or user termination.

    An RFCOMM Bluetooth Socket used to accept incoming connections must be attached tooperating system resources with the bind method. Bindtakes in a tuple specifying theaddress 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 theempty string indicates that any local Bluetooth adapter is acceptable. Once a socket isbound, a call to listen puts the socket into listening mode and it is then ready to accept

    incoming connections.

    Connecting to a remote deviceYou must request theBLUETOOTHpermission in order to perform any Bluetoothcommunication, such as requesting a connection, accepting a connection, and transferringdata. Before your application can communicate over Bluetooth, you need to verify thatBluetooth is supported on the device, and if so, ensure that it is enabled. you need to ensure

    http://developer.android.com/reference/android/bluetooth/BluetoothAdapter.htmlhttp://developer.android.com/reference/android/bluetooth/BluetoothAdapter.htmlhttp://developer.android.com/reference/android/bluetooth/BluetoothAdapter.htmlhttp://developer.android.com/reference/android/bluetooth/BluetoothDevice.htmlhttp://developer.android.com/reference/android/bluetooth/BluetoothDevice.htmlhttp://developer.android.com/reference/android/bluetooth/BluetoothDevice.htmlhttp://developer.android.com/reference/android/bluetooth/BluetoothServerSocket.htmlhttp://developer.android.com/reference/android/bluetooth/BluetoothServerSocket.htmlhttp://developer.android.com/reference/android/bluetooth/BluetoothServerSocket.htmlhttp://developer.android.com/reference/android/bluetooth/BluetoothSocket.htmlhttp://developer.android.com/reference/android/bluetooth/BluetoothSocket.htmlhttp://developer.android.com/reference/android/bluetooth/BluetoothSocket.htmlhttp://developer.android.com/reference/java/net/Socket.htmlhttp://developer.android.com/reference/java/net/Socket.htmlhttp://developer.android.com/reference/java/net/Socket.htmlhttp://developer.android.com/reference/android/Manifest.permission.html#BLUETOOTHhttp://developer.android.com/reference/android/Manifest.permission.html#BLUETOOTHhttp://developer.android.com/reference/android/Manifest.permission.html#BLUETOOTHhttp://developer.android.com/reference/android/Manifest.permission.html#BLUETOOTHhttp://developer.android.com/reference/java/net/Socket.htmlhttp://developer.android.com/reference/android/bluetooth/BluetoothSocket.htmlhttp://developer.android.com/reference/android/bluetooth/BluetoothServerSocket.htmlhttp://developer.android.com/reference/android/bluetooth/BluetoothDevice.htmlhttp://developer.android.com/reference/android/bluetooth/BluetoothAdapter.html
  • 7/25/2019 blutooth chat project report

    9/58

    9

    that Bluetooth is enabled. A dialog will appear requesting user permission to enableBluetooth. Once a connection is made with a remote device for the first time, a pairingrequest is automatically presented to the user. When a device is paired, the basic informationabout that device (such as the device name, class, and MAC address) is saved and can beread 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 thedevice is within range).

    Transferring data over BluetoothCheck the manual that came with your cellular phone and read the section on Bluetoothcapabilities to see if your phone has a Bluetooth password. Note down the password. Poweron 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 secondphone. 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 thenpress the button to send to a connected Bluetooth phone. Enter in the phone number of theother phone if your cell does not prompt you to send to an activated Bluetooth phone inrange.

  • 7/25/2019 blutooth chat project report

    10/58

    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

    1st 3 weeks, 7Feb, 2014 to 1March, 2014:- Designing of database and layout of user

    interface.SRS design.

    1weeks, 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)

  • 7/25/2019 blutooth chat project report

    11/58

    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.

  • 7/25/2019 blutooth chat project report

    12/58

    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

  • 7/25/2019 blutooth chat project report

    13/58

    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 manydifferent components.

    DFD of Royal chat:-

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

  • 7/25/2019 blutooth chat project report

    14/58

    14

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

    DFD of DataBase:-

  • 7/25/2019 blutooth chat project report

    15/58

    15

    DFD of Server-Socket:-

    DFD of DevicesListActivity:-

  • 7/25/2019 blutooth chat project report

    16/58

    16

    Database:-

    SQLite is a relational database management system contained in a C programming library. Incontrast to other database management systems, SQLite is not a separate process that is accessedfrom the client application, but an integral part of it.

    SQLite is ACID-compliant and implements most of the SQL standard, using a dynamically andweakly typed SQL syntax that does not guarantee the domain integrity.

    SQLite is a popular choice as embedded database for local/client storage in application softwaresuch as web browsers. It is arguably the most widely deployed database engine, as it is usedtoday by several widespread browsers, operating systems, and embedded systems, among others.SQLite has many bindings to programming languages.

    http://en.wikipedia.org/wiki/File:SQLite370.svghttp://en.wikipedia.org/wiki/File:SQLite370.svg
  • 7/25/2019 blutooth chat project report

    17/58

    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 supportsINSTEAD OF triggers that provide this functionality). While it supports complex queries, it stillhas 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 typeto a column as in most SQL database systems, types are assigned to individual values; inlanguage terms it is dynamically typed. Moreover, it is weakly typedin some of the same waysthat Perl is: one can insert a string into an integer column (although SQLite will try to convert thestring to an integer first, if the column's preferred type is integer). This adds flexibility tocolumns, especially when bound to a dynamically typed scripting language. However, thetechnique 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 otherproducts. 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:

    packagecom.example.splash_screenn;

    importandroid.app.Activity;importandroid.os.Bundle;

    importandroid.view.Menu;importandroid.view.View;

    import android.widget.ProgressBar;

    publicclasssplash extendsActivity {

    ProgressBar bar;

    @OverrideprotectedvoidonCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.fragment_main);bar=(ProgressBar) findViewById(R.id.progressBar1);

    bar.setVisibility(View.VISIBLE);

  • 7/25/2019 blutooth chat project report

    18/58

    18

    Thread thread=newThread(){publicvoidrun() {

    try{sleep(3000);

    } catch(InterruptedException e) {

    // TODOAuto-generated catch blocke.printStackTrace();

    }finally{

    System.out.println("anil singhania");}

    }

    };

    thread.start();}

    @Override

    protectedvoidonPause() {// TODOAuto-generated method stubfinish();

    super.onPause();}

    @OverridepublicbooleanonCreateOptionsMenu(Menu menu) {

    getMenuInflater().inflate(R.menu.main, menu);

    returntrue;}

    }

    XML L ayout:-

    Fragment_main.xml:

  • 7/25/2019 blutooth chat project report

    19/58

    19

    Screen Shots:

    NavigationDrawer.java

    packagecom.example.royal_chat;

    importandroid.os.Bundle;

    importandroid.annotation.SuppressLint;importandroid.app.Activity;

    importandroid.app.AlertDialog;importandroid.content.DialogInterface;

    importandroid.content.res.Configuration;

    importandroid.support.v4.app.ActionBarDrawerToggle;importandroid.support.v4.view.GravityCompat;

    importandroid.support.v4.widget.DrawerLayout;importandroid.view.Menu;

    importandroid.view.MenuItem;

    importandroid.view.View;import android.widget.AdapterView;

    importandroid.widget.ArrayAdapter;importandroid.widget.ListView;importandroid.widget.TextView;importandroid.widget.Toast;

    publicclassNavigationDrawer extendsActivity {

  • 7/25/2019 blutooth chat project report

    20/58

    20

    privateString[] drawerListArray;

    privateDrawerLayout drawerLayout;privateActionBarDrawerToggle actionBarDrawerToggle;ListView drawerlist;DrawerLayout drawerlayout;

    //for dialogbox

    ListView blueDialog;@SuppressLint("NewApi")

    @OverrideprotectedvoidonCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);setContentView(R.layout.activity_navigation_drawerdemo );

    // get list items from strings.xmldrawerListArray= 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 viewdrawerlist.setAdapter(newArrayAdapter(this,

    R.layout.listcontent, drawerListArray));

    // 2. App Icon

    drawerlayout= (DrawerLayout) findViewById(R.id.drawer_layout);

    // 2.1 create ActionBarDrawerToggleactionBarDrawerToggle= newActionBarDrawerToggle(

    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" arrowgetActionBar().setDisplayHomeAsUpEnabled( true);

    // just styling option

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

    drawerlist.setOnItemClickListener(newDrawerItemClickListener());

    }

    @OverrideprotectedvoidonPostCreate(Bundle savedInstanceState) {

    super.onPostCreate(savedInstanceState);

    // Sync the toggle state after onRestoreInstanceState has occurred.actionBarDrawerToggle.syncState();

    }

    @OverridepublicvoidonConfigurationChanged(Configuration newConfig) {

    super.onConfigurationChanged(newConfig);

  • 7/25/2019 blutooth chat project report

    21/58

    21

    actionBarDrawerToggle.onConfigurationChanged(newConfig);

    }

    @OverridepublicbooleanonOptionsItemSelected(MenuItem item) {

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

    if(actionBarDrawerToggle.onOptionsItemSelected(item)) {returntrue;

    }

    returnsuper.onOptionsItemSelected(item);}

    privateclassDrawerItemClickListener implementsListView.OnItemClickListener {@Override

    publicvoidonItemClick(AdapterView parent, View view, intposition, longid){

    Toast.makeText(getApplicationContext(), ((TextView)view).getText(),Toast.LENGTH_LONG).show();// drawerLayout.closeDrawer(drawerlist);

    switch(position) {case0:

    alertMessage();break;

    }drawerLayout.closeDrawer(drawerlist);

    }publicvoidalertMessage() {

    // TODOAuto-generated method stub

    DialogInterface.OnClickListener dialoginterfc=new

    DialogInterface.OnClickListener() {

    @OverridepublicvoidonClick(DialogInterface dialog, intwhich) {

    // TODOAuto-generated method stub

    switch(which) {

    caseDialogInterface.BUTTON_NEGATIVE:

    //no button is clicked do nothingToast.makeText(getApplicationContext(), "Oh! No",

    Toast.LENGTH_LONG).show();break;

    caseDialogInterface.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

  • 7/25/2019 blutooth chat project report

    22/58

    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();}

    }@OverridepublicbooleanonCreateOptionsMenu(Menu menu) {

    // Inflate the menu; this adds items to the action bar if it is present.

    getMenuInflater().inflate(R.menu.main, menu);returntrue;

    }

    }

    XML Layout:

    Screen Shot:

  • 7/25/2019 blutooth chat project report

    23/58

    23

    BluetoothChat.java

    packagecom.example.bluetoothchat;

    importandroid.app.Activity;

    importandroid.os.Bundle;importandroid.view.Menu;

    import android.bluetooth.BluetoothAdapter;

    importandroid.bluetooth.BluetoothDevice;importandroid.content.Intent;importandroid.os.Handler;importandroid.os.Message;

    importandroid.util.Log;importandroid.view.KeyEvent;

    importandroid.view.MenuInflater;

    importandroid.view.MenuItem;importandroid.view.View;importandroid.view.Window;importandroid.view.View.OnClickListener;

    importandroid.view.inputmethod.EditorInfo;importandroid.widget.ArrayAdapter;

    importandroid.widget.Button;importandroid.widget.EditText;importandroid.widget.ListView;

    importandroid.widget.TextView;importandroid.widget.Toast;

    /*** This is the main Activity that displays the current chat session.

    */

  • 7/25/2019 blutooth chat project report

    24/58

    24

    publicclassBluetoothChat extendsActivity {

    // DebuggingprivatestaticfinalString TAG= "BluetoothChat";privatestaticfinalbooleanD= true;

    // Message types sent from the BluetoothChatService Handler

    publicstaticfinalintMESSAGE_STATE_CHANGE= 1;publicstaticfinalintMESSAGE_READ= 2;

    publicstaticfinalintMESSAGE_WRITE= 3;publicstaticfinalintMESSAGE_DEVICE_NAME= 4;publicstaticfinalintMESSAGE_TOAST= 5;

    // Key names received from the BluetoothChatService HandlerpublicstaticfinalString DEVICE_NAME= "device_name";

    publicstaticfinalString TOAST= "toast";

    // Intent request codes

    privatestaticfinalintREQUEST_CONNECT_DEVICE= 1;privatestaticfinalintREQUEST_ENABLE_BT= 2;

    // Layout Views

    privateTextView mTitle;

    privateListView mConversationView;privateEditText mOutEditText;

    privateButton mSendButton;

    // Name of the connected device

    privateString mConnectedDeviceName= null;// Array adapter for the conversation thread

    privateArrayAdapter mConversationArrayAdapter ;// String buffer for outgoing messages

    privateStringBuffer mOutStringBuffer;// Local Bluetooth adapter

    privateBluetoothAdapter mBluetoothAdapter= null;

    // Member object for the chat servicesprivateBluetoothChatService mChatService= null;

    @Override

    publicvoidonCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    if(D) Log.e(TAG, "+++ ON CREATE +++");

    // Set up the window layoutrequestWindowFeature(Window. FEATURE_ACTION_BAR);

    setContentView(R.layout. activity_main);getWindow().setFeatureInt(Window. FEATURE_ACTION_BAR, R.layout.custom_title);

    // Set up the custom titlemTitle= (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();

  • 7/25/2019 blutooth chat project report

    25/58

    25

    // If the adapter is null, then Bluetooth is not supportedif(mBluetoothAdapter== null) {

    Toast.makeText(this, "Bluetooth is not available",Toast.LENGTH_LONG).show();

    finish();

    return;}

    }

    @OverridepublicvoidonStart() {

    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 = newIntent(BluetoothAdapter.ACTION_REQUEST_ENABLE);

    startActivityForResult(enableIntent, REQUEST_ENABLE_BT);// Otherwise, setup the chat session} else{

    if(mChatService== null) setupChat();}

    }

    @Override

    publicsynchronizedvoidonResume() {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

    alreadyif(mChatService.getState() == BluetoothChatService.STATE_NONE) {// Start the Bluetooth chat servicesmChatService.start();

    }

    }}

    privatevoidsetupChat() {

    Log.d(TAG, "setupChat()");

    // Initialize the array adapter for the conversation thread

    mConversationArrayAdapter = newArrayAdapter(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);

  • 7/25/2019 blutooth chat project report

    26/58

    26

    // Initialize the send button with a listener that for click eventsmSendButton= (Button) findViewById(R.id.button_send);mSendButton.setOnClickListener(newOnClickListener() {

    publicvoidonClick(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 connectionsmChatService= newBluetoothChatService(this, mHandler);

    // Initialize the buffer for outgoing messagesmOutStringBuffer= newStringBuffer("");

    }

    @OverridepublicsynchronizedvoidonPause() {

    super.onPause();

    if(D) Log.e(TAG, "- ON PAUSE -");}

    @Override

    publicvoidonStop() {

    super.onStop();if(D) Log.e(TAG, "-- ON STOP --");

    }

    @Override

    publicvoidonDestroy() {

    super.onDestroy();

    // Stop the Bluetooth chat services//if (mChatService != null) mChatService.stop();

    //if(D) Log.e(TAG, "--- ON DESTROY ---");}

    privatevoidensureDiscoverable() {

    if(D) Log.d(TAG, "ensure discoverable");

    if(mBluetoothAdapter.getScanMode() !=BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE ) {

    Intent discoverableIntent = newIntent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);

    discoverableIntent.putExtra(BluetoothAdapter. EXTRA_DISCOVERABLE_DURATION,300);

    startActivity(discoverableIntent);

    }}

    /**

    * Sends a message.* @parammessage A string of text to send.

    */

  • 7/25/2019 blutooth chat project report

    27/58

    27

    privatevoidsendMessage(String message) {

    // Check that we're actually connected before trying anythingif(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 writebyte[] 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=

    newTextView.OnEditorActionListener() {

    publicbooleanonEditorAction(TextView view, intactionId, 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");returntrue;

    }};

    // The Handler that gets information back from the BluetoothChatServiceprivatefinalHandler mHandler= newHandler() {

    @OverridepublicvoidhandleMessage(Message msg) {

    switch(msg.what) {

    caseMESSAGE_STATE_CHANGE:

    if(D) Log.i(TAG, "MESSAGE_STATE_CHANGE: "+ msg.arg1);

    switch(msg.arg1) {caseBluetoothChatService.STATE_CONNECTED:

    mTitle.setText(R.string.title_connected_to);mTitle.append(mConnectedDeviceName);

    mConversationArrayAdapter .clear();break;

    caseBluetoothChatService.STATE_CONNECTING:

    mTitle.setText(R.string.title_connecting);break;

    caseBluetoothChatService.STATE_LISTEN:

    break;caseBluetoothChatService.STATE_NONE:

    mTitle.setText(R.string.title_not_connected);

  • 7/25/2019 blutooth chat project report

    28/58

    28

    break;

    }break;

    caseMESSAGE_WRITE:byte[] writeBuf = (byte[]) msg.obj;

    // construct a string from the buffer

    String writeMessage = newString(writeBuf);mConversationArrayAdapter .add("Me: "+ writeMessage);

    break;caseMESSAGE_READ:

    byte[] readBuf = (byte[]) msg.obj;// construct a string from the valid bytes in the buffer

    String readMessage = newString(readBuf, 0, msg.arg1);mConversationArrayAdapter .add(mConnectedDeviceName+": "+

    readMessage);

    break;caseMESSAGE_DEVICE_NAME:

    // save the connected device's namemConnectedDeviceName= msg.getData().getString(DEVICE_NAME);

    Toast.makeText(getApplicationContext(), "Connected to "+ mConnectedDeviceName, Toast.LENGTH_SHORT).show();

    break;

    caseMESSAGE_TOAST:Toast.makeText(getApplicationContext(),

    msg.getData().getString(TOAST),Toast.LENGTH_SHORT).show();

    break;}

    }

    };

    publicvoidonActivityResult(intrequestCode, intresultCode, Intent data) {

    if(D) Log.d(TAG, "onActivityResult "+ resultCode);

    switch(requestCode) {

    caseREQUEST_CONNECT_DEVICE:// When DeviceListActivity returns with a device to connect

    if(resultCode == Activity.RESULT_OK) {// Get the device MAC addressString address = data.getExtras()

    .getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);

    // Get the BLuetoothDevice objectBluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);

    // Attempt to connect to the devicemChatService.connect(device);

    }break;

    caseREQUEST_ENABLE_BT:

    // When the request to enable Bluetooth returnsif(resultCode == Activity.RESULT_OK) {

    // Bluetooth is now enabled, so set up a chat sessionsetupChat();

    } else{// User did not enable Bluetooth or an error occured

    Log.d(TAG, "BT not enabled");

  • 7/25/2019 blutooth chat project report

    29/58

    29

    Toast.makeText(this, R.string.bt_not_enabled_leaving,

    Toast.LENGTH_SHORT).show();finish();

    }}

    }

    @Override

    publicbooleanonCreateOptionsMenu(Menu menu) {MenuInflater inflater = getMenuInflater();inflater.inflate(R.menu.main, menu);returntrue;

    }

    @Override

    publicbooleanonOptionsItemSelected(MenuItem item) {switch(item.getItemId()) {

    caseR.id.scan:// Launch the DeviceListActivity to see devices and do scan

    Intent serverIntent = newIntent(this, DeviceListActivity.class);startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);

    returntrue;

    caseR.id.discoverable:// Ensure this device is discoverable by othersensureDiscoverable();returntrue;

    }

    returnfalse;}

    }

    BluetoothChatServices:

    packagecom.example.bluetoothchat;

    importjava.io.IOException;

    importjava.io.InputStream;importjava.io.OutputStream;

    importjava.util.UUID;

    import android.bluetooth.BluetoothAdapter;

    importandroid.bluetooth.BluetoothDevice;importandroid.bluetooth.BluetoothServerSocket;

    importandroid.bluetooth.BluetoothSocket;

    importandroid.content.Context;importandroid.os.Bundle;

  • 7/25/2019 blutooth chat project report

    30/58

    30

    importandroid.os.Handler;

    importandroid.os.Message;importandroid.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.*/

    publicclassBluetoothChatService {// Debugging

    privatestaticfinalString TAG= "BluetoothChatService";privatestaticfinalbooleanD= true;

    // Name for the SDP record when creating server socketprivatestaticfinalString NAME= "BluetoothChat";

    // Unique UUID for this application

    privatestaticfinalUUIDMY_UUID= UUID.fromString("fa87c0d0-afac-11de-8a39-0800200c9a66");

    // Member fieldsprivatefinalBluetoothAdapter mAdapter;

    privatefinalHandler mHandler;privateAcceptThread mAcceptThread;

    privateConnectThread mConnectThread;

    privateConnectedThread mConnectedThread;privateintmState;

    // Constants that indicate the current connection state

    publicstaticfinalintSTATE_NONE= 0; // we're doing nothing

    publicstaticfinalintSTATE_LISTEN= 1; // now listening for incoming

    connections

    publicstaticfinalintSTATE_CONNECTING= 2; // now initiating an outgoingconnection

    publicstaticfinalintSTATE_CONNECTED= 3; // now connected to a remote device

    /*** Constructor. Prepares a new BluetoothChat session.

    * @paramcontext The UI Activity Context

    * @paramhandler A Handler to send messages back to the UI Activity*/

    publicBluetoothChatService(Context context, Handler handler) {mAdapter= BluetoothAdapter.getDefaultAdapter();

    mState= STATE_NONE;mHandler= handler;

    }

    /*** Set the current state of the chat connection* @paramstate An integer defining the current connection state

    */privatesynchronizedvoidsetState(intstate) {

    if(D) Log.d(TAG, "setState() "+ mState+ " -> "+ state);

  • 7/25/2019 blutooth chat project report

    31/58

  • 7/25/2019 blutooth chat project report

    32/58

    32

    }

    /*** Start the ConnectedThread to begin managing a Bluetooth connection* @paramsocket The BluetoothSocket on which the connection was made

    * @paramdevice The BluetoothDevice that has been connected

    */publicsynchronizedvoidconnected(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= newConnectedThread(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 = newBundle();bundle.putString(BluetoothChat. DEVICE_NAME, device.getName());

    msg.setData(bundle);mHandler.sendMessage(msg);

    setState(STATE_CONNECTED);

    }

    /**

    * Stop all threads*/

    publicsynchronizedvoidstop() {

    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* @paramout The bytes to write* @see ConnectedThread#write(byte[])*/

    publicvoidwrite(byte[] out) {// Create temporary object

    ConnectedThread r;

  • 7/25/2019 blutooth chat project report

    33/58

    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. */

    privatevoidconnectionFailed() {setState(STATE_LISTEN);

    // Send a failure message back to the ActivityMessage msg = mHandler.obtainMessage(BluetoothChat.MESSAGE_TOAST);Bundle bundle = newBundle();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.*/

    privatevoidconnectionLost() {setState(STATE_LISTEN);

    // Send a failure message back to the ActivityMessage msg = mHandler.obtainMessage(BluetoothChat.MESSAGE_TOAST);Bundle bundle = newBundle();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).

    */privateclassAcceptThread extendsThread {

    // The local server socketprivatefinalBluetoothServerSocket mmServerSocket;

    publicAcceptThread() {

    BluetoothServerSocket tmp = null;

    // Create a new listening server sockettry{

    tmp = mAdapter.listenUsingRfcommWithServiceRecord( NAME,MY_UUID);

    } catch(IOException e) {Log.e(TAG, "listen() failed", e);

    }

  • 7/25/2019 blutooth chat project report

    34/58

    34

    mmServerSocket= tmp;

    }

    publicvoidrun() {if(D) Log.d(TAG, "BEGIN mAcceptThread"+ this);

    setName("AcceptThread");

    BluetoothSocket socket = null;

    // Listen to the server socket if we're not connectedwhile(mState!= STATE_CONNECTED) {

    try{// This is a blocking call and will only return on a

    // successful connection or an exceptionsocket = mmServerSocket.accept();

    } catch(IOException e) {

    Log.e(TAG, "accept() failed", e);break;

    }

    // If a connection was acceptedif(socket != null) {

    synchronized(BluetoothChatService.this) {

    switch(mState) {caseSTATE_LISTEN:

    caseSTATE_CONNECTING:// Situation normal. Start the connected thread.

    connected(socket, socket.getRemoteDevice());

    break;caseSTATE_NONE:

    caseSTATE_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");

    }

    publicvoidcancel() {if(D) Log.d(TAG, "cancel "+ this);

    try{

    mmServerSocket.close();} catch(IOException e) {

    Log.e(TAG, "close() of server failed", e);}

    }}

  • 7/25/2019 blutooth chat project report

    35/58

    35

    /*** This thread runs while attempting to make an outgoing connection * with a device. It runs straight through; the connection either* succeeds or fails.

    */

    privateclassConnectThread extendsThread {privatefinalBluetoothSocket mmSocket;

    privatefinalBluetoothDevice mmDevice;

    publicConnectThread(BluetoothDevice device) {mmDevice= device;

    BluetoothSocket tmp = null;

    // Get a BluetoothSocket for a connection with the

    // given BluetoothDevicetry{

    tmp = device.createRfcommSocketToServiceRecord(MY_UUID);} catch(IOException e) {

    Log.e(TAG, "create() failed", e);}mmSocket= tmp;

    }

    publicvoidrun() {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 exceptionmmSocket.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 modeBluetoothChatService.this.start();

    return;

    }

    // Reset the ConnectThread because we're donesynchronized(BluetoothChatService.this) {

    mConnectThread= null;}

  • 7/25/2019 blutooth chat project report

    36/58

  • 7/25/2019 blutooth chat project report

    37/58

    37

    } catch(IOException e) {

    Log.e(TAG, "disconnected", e);connectionLost();break;

    }

    }

    }

    /*** Write to the connected OutStream.* @parambuffer The bytes to write*/

    publicvoidwrite(byte[] buffer) {try{

    mmOutStream.write(buffer);

    // Share the sent message back to the UI ActivitymHandler.obtainMessage(BluetoothChat.MESSAGE_WRITE, -1, -1, buffer)

    .sendToTarget();

    } catch(IOException e) {Log.e(TAG, "Exception during write", e);}

    }

    publicvoidcancel() {try{

    mmSocket.close();} catch(IOException e) {

    Log.e(TAG, "close() of connect socket failed", e);

    }}

    }

    }

    DeviceListActivity:

    packagecom.example.bluetoothchat;

    importjava.util.Set;

    importandroid.app.Activity;

    import android.bluetooth.BluetoothAdapter;

    importandroid.bluetooth.BluetoothDevice;importandroid.content.BroadcastReceiver;

    importandroid.content.Context;importandroid.content.Intent;

    import android.content.IntentFilter;importandroid.os.Bundle;

    importandroid.util.Log;

    importandroid.view.View;importandroid.view.Window;importandroid.view.View.OnClickListener;

  • 7/25/2019 blutooth chat project report

    38/58

    38

    import android.widget.AdapterView;

    importandroid.widget.ArrayAdapter;importandroid.widget.Button;importandroid.widget.ListView;importandroid.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.

    */publicclassDeviceListActivity extendsActivity {

    // Debugging

    privatestaticfinalString TAG= "DeviceListActivity";privatestaticfinalbooleanD= true;

    // Return Intent extra

    publicstaticString EXTRA_DEVICE_ADDRESS= "device_address";

    // Member fields

    privateBluetoothAdapter mBtAdapter;privateArrayAdapter mPairedDevicesArrayAdapter ;

    privateArrayAdapter mNewDevicesArrayAdapter ;

    @Override

    protectedvoidonCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);

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

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

    // Initialize the button to perform device discoveryButton scanButton = (Button) findViewById(R.id.button_scan);scanButton.setOnClickListener( newOnClickListener() {

    publicvoidonClick(View v) {

    doDiscovery();v.setVisibility(View.GONE);

    }});

    // Initialize array adapters. One for already paired devices and

    // one for newly discovered devices

    mPairedDevicesArrayAdapter = newArrayAdapter(this,R.layout.device_name);

    mNewDevicesArrayAdapter= newArrayAdapter(this,R.layout.device_name);

    // Find and set up the ListView for paired devices

    ListView pairedListView = (ListView) findViewById(R.id.paired_devices);

  • 7/25/2019 blutooth chat project report

    39/58

    39

    pairedListView.setAdapter( mPairedDevicesArrayAdapter );

    pairedListView.setOnItemClickListener(mDeviceClickListener);

    // Find and set up the ListView for newly discovered devicesListView newDevicesListView = (ListView) findViewById(R.id.new_devices);

    newDevicesListView.setAdapter( mNewDevicesArrayAdapter);

    newDevicesListView.setOnItemClickListener( mDeviceClickListener);

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

    // Register for broadcasts when discovery has finishedfilter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);

    this.registerReceiver(mReceiver, filter);

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

    // Get a set of currently paired devicesSet pairedDevices = mBtAdapter.getBondedDevices();

    // If there are paired devices, add each one to the ArrayAdapterif(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);

    }

    }

    @OverrideprotectedvoidonDestroy() {

    super.onDestroy();

    // Make sure we're not doing discovery anymore

    if(mBtAdapter!= null) {mBtAdapter.cancelDiscovery();

    }

    // Unregister broadcast listenersthis.unregisterReceiver(mReceiver);

    }

    /*** Start device discover with the BluetoothAdapter*/

    privatevoiddoDiscovery() {if(D) Log.d(TAG, "doDiscovery()");

  • 7/25/2019 blutooth chat project report

    40/58

    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 BluetoothAdaptermBtAdapter.startDiscovery();

    }

    // The on-click listener for all devices in the ListViews

    privateOnItemClickListener mDeviceClickListener= newOnItemClickListener() {publicvoidonItemClick(AdapterView av, View v, intarg2, longarg3) {

    // 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 ViewString info = ((TextView) v).getText().toString();String address = info.substring(info.length() - 17);

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

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

    }

    };

    // The BroadcastReceiver that listens for discovered devices and// changes the title when discovery is finished

    privatefinalBroadcastReceiver mReceiver= newBroadcastReceiver() {@Override

    publicvoidonReceive(Context context, Intent intent) {

    String action = intent.getAction();

    // When discovery finds a deviceif(BluetoothDevice.ACTION_FOUND.equals(action)) {

    // Get the BluetoothDevice object from the IntentBluetoothDevice device =

    intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

    // If it's already paired, skip it, because it's been listed alreadyif(device.getBondState() != BluetoothDevice.BOND_BONDED) {

    mNewDevicesArrayAdapter.add(device.getName() + "\n"+device.getAddress());

    }// When discovery is finished, change the Activity title

    } elseif(BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {

  • 7/25/2019 blutooth chat project report

    41/58

    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;

  • 7/25/2019 blutooth chat project report

    42/58

    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);

  • 7/25/2019 blutooth chat project report

    43/58

    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);

    }

  • 7/25/2019 blutooth chat project report

    44/58

    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}.

    */

  • 7/25/2019 blutooth chat project report

    45/58

    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));

    }

    }

  • 7/25/2019 blutooth chat project report

    46/58

    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);

  • 7/25/2019 blutooth chat project report

    47/58

    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

    */

  • 7/25/2019 blutooth chat project report

    48/58

    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 {

    }

    /**

    * 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;

  • 7/25/2019 blutooth chat project report

    49/58

    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 {

  • 7/25/2019 blutooth chat project report

    50/58

    50

    public SearchAction() {

    super(R.drawable.actionbar_search);

    }

    }

    */

    }

    XML Layouts:

    Activity_main:-

  • 7/25/2019 blutooth chat project report

    51/58

    51

    devicelist_activity.xml

  • 7/25/2019 blutooth chat project report

    52/58

    52

    android:layout_width="fill_parent"

    android:layout_height="wrap_content"android:stackFromBottom="true"android:layout_weight="1"

    />

    Message.xml:-

    Devicename.xml:-

    Actionbar.xml

  • 7/25/2019 blutooth chat project report

    53/58

    53

    android:orientation="horizontal"

    >

  • 7/25/2019 blutooth chat project report

    54/58

    54

    android:layout_margin="0dp"

    android:padding="0dp"android:background="@color/actionbar_separator" />

  • 7/25/2019 blutooth chat project report

    55/58

    55

    8. TESTING

    TECHNICAL TOOLS:-

    ARM architecture:

    ARMis a family of instruction set architectures for computer processors based on a reducedinstruction set computing (RISC) architecture developed by British company ARM Holdings.

    A RISC-based computer design approach means ARM processors require significantly fewertransistors than typical processors in average computers. This approach reduces costs, heat andpower use. These are desirable traits for light, portable, battery-powered devicesincludingsmartphones, laptops, tablet and notepad computers, and other embedded systems. A simplerdesign facilitates more efficient multi-core CPUs and higher core counts at lower cost, providinghigher processing power and improved energy efficiency for servers and supercomputers.ARMHoldings develops the instruction set and architecture for ARM-based products, but does notmanufacture products. The company periodically releases updates to its cores. Current coresfrom ARM Holdings support a 32-bit address space and 32-bit arithmetic; the recentlyintroduced 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 laterversions of the architecture also support a variable-length instruction set that provides both 32-bitand 16-bit-wide instructions for improved code density. Some cores can also provide hardwareexecution of Java bytecodes.

    Testing Log

  • 7/25/2019 blutooth chat project report

    56/58

    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.

  • 7/25/2019 blutooth chat project report

    57/58

    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.

  • 7/25/2019 blutooth chat project report

    58/58

    11.BIBLIOGRAPHY

    1. www.Betasoftsystem.com2. msdn.mircosoft.com

    3.Googlemy.safaribooksonline.com,codeproject.com etc

    4. Daily Dairy

    5. JAVATPOINT Android

    http://www.betasoftsystem.com/http://www.betasoftsystem.com/http://www.betasoftsystem.com/