Professional Documents
Culture Documents
A DISSERTATION
Submitted by
PUNESH SHARMA
Examiners
________________________
________________________
________________________
Supervisor (s)
Mr. JAVED WASIM
Chairman
________________________
Date :____________
Place :____________
Format 1.2
DECLARATION
I declare that this written submission represents my ideas in my own words and where others' ideas
or words have been included, I have adequately cited and referenced the original sources. I also
declare that I have adhered to all principles of academic honesty and integrity and have not
misrepresented or fabricated or falsified any idea/data/fact/source in my submission. I understand
that any violation of the above will be cause for disciplinary action by the Institute and can also
evoke penal action from the sources which have thus not been properly cited or from whom proper
permission has not been taken when needed.
_________________________________
(Signature)
Punesh sharma
(Roll No. 20150980)
Date: __________
CERTIFICATE Format 1.3
This is certified that the dissertation titled BLUETOOTH CHATT ING APP
by PUNESH SHARMA Degree in partial fulfillment of the requirements for the
award of MASTER IN COMPUTER APPLICATION is an original work carried
out by him/her under my/our supervision and guidance. It is certified that the work has
not been submitted anywhere else for the award of any other diploma or degree of this
or any other University.
Supervisor
(Name & Signature)
Co-Supervisor
(Name & Signature)
ACKNOWLEDGEMENT
I sincerely thank MCN SOLUTIONS PVT LTD for providing me the project training and all
necessary resources and expertise for this purpose.
I am deeply grateful to MANI JI, Android Developer who gave me opportunity to work under
his able guidance. I sincerely thank him for showing me direction and constantly providing me with
words of inspiration.
I am heartily thankful to, Dr. SUBODH SHARMA (HOD of DCA, IET Mangalayatan
University Aligarh U.P) for showing me direction and constantly providing me with words of
inspiration.
I am deeply grateful to Mr. JAVED WASIM who gave me opportunity to work under his able
guidance. I sincerely thank him for showing me direction and constantly providing me with words of
inspiration finally I would like to thanks my Parents, Friends and Relatives for their moral support,
appreciation and encouragement that made the project a success.
PUNESH SHARMA
Enroll.No.
20150980
Format1.4
TABLE OF CONTENTS
1. IntroductionPage no. 07
4. REQUIREMENT ANALYSIS
4.1 Problem Statement......... Page no. 11
4.2 The Challenge- Where to begin... Page no. 12
4.3Software and system requirement specification Page no. 13
4.4System Requirement. Page no. 14
It's secure; this app allows two Android devices to carry out two-way text chat over Bluetooth. It
demonstrates all the fundamental Bluetooth API capabilities, such as: (1) Scanning for other
Bluetooth devices (2) Querying the local Bluetooth adapter for paired Bluetooth devices (3)
Establishing RFCOMM channels/sockets (4) Connecting to a remote device (5) Transferring data
over Bluetooth.
You dont have 3G or cannot find Wi-Fi? With this application you can easily
connect via Bluetooth to anyone nearby and start chatting!
It connects 2 phones in a second and it works in a range of about 50 meters
depending on the environment (Bluetooth does not like walls and closed
doors).
This can be used to send short messages over short distances. Now you can
stay in touch with your friends without paying single bucks. It enables free
chatting. Messages are sent directly between devices. The distance depends
on the devices. Smart Bluetooth Chat is a messaging app. It enables its users
to send messages. Enjoy talking to your friends without Wi-Fi or Internet.
Just pair two android devices using Bluetooth. You can initiate, fast, and easy
to use.
Company Profile
C#, Visual Basic .NET, ASP.NET, ADO.NET, GDI+, Windows Forms, ASP.NET
Web Forms, Web Services, Tablet PC, Pocket PC, Windows, CR.NET, .NET
Multithreading, DirectX, SQL Server, .NET Remoting, Speech .NET
In this type of projects, MCN Solutions will give an estimated time and cost
and we deliver the project within the specified duration.
3-Technology Used
What is Android?
It comes from Google, who actually acquired Android in 2005 (no, Google
didn't invent it). The search giant performs regular updates along with an
annual major update.The operating system is based on the Linux kernel if
you have friends who work in IT, you may have heard of it. This is the GNU /
Linux operating system based structure, which is a unix type system
(portable operating system, multitasking and multi-user). The Linux kernel is
one of the most prominent examples of free software.
Android doesn't look different on every device, but it does have a number of
different versions. Android is open-source, which means that manufacturers
are free to customize the software and make it their own.
Android is the most used mobile operating system. It is used by over billion
people. Android is also the fastest growing operating system on the earth.
Android has billions of users. A number of users increase the number of
applications and software under the name of Android.
Android Multitasking
Most of us love this feature of the android. Users can do lots of tasks at once.
Users can open several applications at once and manage them all too.
Android has great UI which makes easy for users to do multitasking.
Android Malware/Virus/Security
4-REQUIREMENT ANALYSIS
Problem statement
If you are planning to develop an app, your focus should be more on what
not to do than on what to do. There are several challenges faced by
developers every time they start working on a new mobile app.
2. Getting the App Funded: Now that you have a killer app idea, how do
you get it funded? Depending on the nature of the app, the cost of
development can be anywhere from $3,000 to $150,000. How do you get the
money?
Solution: Before you meet the right investors, there are several ways you
can raise funds. Approach your social circle, apply for loans, ask friends and
relatives and look for joint venture companies which invest in such apps. You
may also try crowdfunding platforms like Kickstarter and AppBackrare great
starting points. App contests can also be the way to go if you have a winning
idea in mind.
3. Dealing with the Screen Real Estate: Users have many different
devices with different screen sizes. And designing only for the latest platform
is a big no-no. So the challenge is to create an app which can run across as
many devices as possible. Countless mobile platforms have different
limitations based on screen sizes, OS requirements, embedded technologies,
pixel intensities etc. However, its not only about the devices. You need to
consider the OS as well. iOS, Android and Windows each of these three
main systems has its own UI objects and patterns. So be prepared for some
bug fixing every now and then.
Solution: Responsive Design. It gives screens more liquidity and thus can be
adjusted to suit different formats and various screen sizes. Facebook is a
great example.
To deal with technical OS issues, having a marked testing phase helps.
Releasing a beta version of the app is also recommended.
5. Keeping it Simple and Clear: An app that makes users think isnt a
good app. The challenge is to design an application which is self-explanatory.
But keep in mind that if the functioning of the app is clears to you (the
developer), it isnt necessarily clear to the users as well.
Solution: The trick is to use a simple and clear structure and give brief
instructions, tutorials etc. explaining what needs to be done and how. You
may use thumbnails and icons to display information in a compact manner.
However, make sure these icons correspond to the native UI elements of
each OS. You can refer to the UI guidelines provided by platforms like
Android, Apple iOS and Windows to choose UI patterns users are already
acquainted with.
7. Mobile Content Management: The need for mobile app content is ever
growing. The call of the hour is to include rich content videos, images,
animations etc. However, the performance fails of wireless networks and
frequent connection drops make it difficult to deliver reliable yet rich content
that consumes a lot of bandwidth. Besides, app stores like Google Play
require you to bundle all your rich content into monolithic expansion files.
This means whenever you want to update your content, you need to release
a new version of the app.
8. Connecting with the user: The mobile app market is changing rapidly.
Innovation and creativity have made this ecosystem highly active. Thus
connecting with the users is crucial. And no, it is not just about the features
you include in the app.
9. Promoting and Marketing the App: Its a clich that most developers
dont care about marketing their apps. However, its not true. There are
several challenges which developers face while taking their apps to the
market. The bottleneck competition, tight timelines and lack of right
platforms push developers into keeping app marketing on the back burner.
10. Lack of Transparency by App Stores: How your app will fare depends
partially on the app store you are submitting it to. However, app stores arent
100% transparent. There is no way of knowing the market size for different
categories or which category is trending globally. In other words, is there a
market for the app you are developing? If yes, where is it? Without knowing
such basic facts you can only depend on your gut instincts to market the
app.
Solution: The only way out is to research. Go through the reports released
by various app stores. Based on the data you can get an estimate of where
and why your app is most likely to sell.
Software and system requirement specification (Development)
Windows-Based Requirements
8 GB of memory
Mac-Based Requirements
Apple computers must meet the following minimal hardware and software
requirements.
x86-64 processor (64-bit Mac with an Intel Core 2 Duo, Intel Core i3,
Intel Core i5, Intel Core i7, or Xeon processor)
8 GB of memory
Along with those previously listed, each development platform has additional
requirements. Detailed information on how to meet these requirements is
provided in the procedures for installing each platform's respective software
development kit (SDK) and emulator.
iOS
The latest version of Xcode, the Apple SDK for creating iOS apps
Android
Windows Mobile
8 GB of internal storage
4 GB memory
BlackBerry
System Requirement
Robust and flexible build system ... System Requirements ... IDE + 1.5 GB for
Android SDK and emulator system image); 1280 x 800 minimum screen
resolution.
You can choose which version of the Android system you want to run in the ... SDK
Tools 25.0.10 or higher; System requirements for the accelerated emulator.
5-System Design and Algorithm
System Design
Algorithm
Step 1. Application START.
Bluetooth
Chat
App
Open
0 Level DFD..
Message Delivered
Open Connected
Bluetooth Enter Text
User On/Off
Not Not-Connected
1 Level DFD
package com.mcn.bluetoothchat.services;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import com.mcn.bluetoothchat.utils.Constants;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;
/**
* Created by .on 30/3/17.
*/
public class BluetoothChatService {
// Debugging
private static final String TAG = "BluetoothChatService";
// Member fields
private final BluetoothAdapter mAdapter;
private final Handler mHandler;
private AcceptThread mSecureAcceptThread;
private AcceptThread mInsecureAcceptThread;
private ConnectThread mConnectThread;
private ConnectedThread mConnectedThread;
private int mState;
private int mNewState;
/**
* 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;
mNewState = mState;
mHandler = handler;
}
/**
* Update UI title according to the current state of the chat connection
*/
private synchronized void updateUserInterfaceTitle() {
mState = getState();
mNewState = mState;
// Give the new state to the Handler so the UI Activity can update
mHandler.obtainMessage(Constants.MESSAGE_STATE_CHANGE, mNewState,
-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() {
/**
* Start the ConnectThread to initiate a connection to a remote device.
*
* @param device The BluetoothDevice to connect
* @param secure Socket Security type - Secure (true) , Insecure (false)
*/
public synchronized void connect(BluetoothDevice device, boolean secure) {
/**
* 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, final String socketType) {
// Cancel the accept thread because we only want to connect to one device
if (mSecureAcceptThread != null) {
mSecureAcceptThread.cancel();
mSecureAcceptThread = null;
}
if (mInsecureAcceptThread != null) {
mInsecureAcceptThread.cancel();
mInsecureAcceptThread = null;
}
/**
* Stop all threads
*/
public synchronized void stop() {
if (mConnectThread != null) {
mConnectThread.cancel();
mConnectThread = null;
}
if (mConnectedThread != null) {
mConnectedThread.cancel();
mConnectedThread = null;
}
if (mSecureAcceptThread != null) {
mSecureAcceptThread.cancel();
mSecureAcceptThread = null;
}
if (mInsecureAcceptThread != null) {
mInsecureAcceptThread.cancel();
mInsecureAcceptThread = null;
}
mState = STATE_NONE;
// Update UI title
updateUserInterfaceTitle();
}
/**
* 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;
// 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() {
// Send a failure message back to the Activity
Message msg = mHandler.obtainMessage(Constants.MESSAGE_TOAST);
Bundle bundle = new Bundle();
bundle.putString(Constants.TOAST, "Unable to connect device");
msg.setData(bundle);
mHandler.sendMessage(msg);
mState = STATE_NONE;
// Update UI title
updateUserInterfaceTitle();
/**
* Indicate that the connection was lost and notify the UI Activity.
*/
private void connectionLost() {
// Send a failure message back to the Activity
Message msg = mHandler.obtainMessage(Constants.MESSAGE_TOAST);
Bundle bundle = new Bundle();
bundle.putString(Constants.TOAST, "Device connection was lost");
msg.setData(bundle);
mHandler.sendMessage(msg);
mState = STATE_NONE;
// Update UI title
updateUserInterfaceTitle();
/**
* 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;
private String mSocketType;
public AcceptThread(boolean secure) {
BluetoothServerSocket tmp = null;
mSocketType = secure ? "Secure" : "Insecure";
}
mmServerSocket = tmp;
mState = STATE_LISTEN;
}
}
}
}
/**
* 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;
private String mSocketType;
/**
* 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;
mmInStream = tmpIn;
mmOutStream = tmpOut;
mState = STATE_CONNECTED;
}
/**
* Write to the connected OutStream.
*
* @param buffer The bytes to write
*/
public void write(byte[] buffer) {
try {
mmOutStream.write(buffer);
package com.mcn.bluetoothchat.activity;
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.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import com.mcn.bluetoothchat.R;
import java.util.Set;
/**
* Created by amit on 30/3/17.
*/
/**
* Return Intent extra
*/
public static String EXTRA_DEVICE_ADDRESS = "device_address";
/**
* Member fields
*/
private BluetoothAdapter mBtAdapter;
/**
* Newly discovered devices
*/
private ArrayAdapter<String> mNewDevicesArrayAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
@Override
protected void onDestroy() {
super.onDestroy();
/**
* Start device discover with the BluetoothAdapter
*/
private void doDiscovery() {
/**
* The on-click listener for all devices in the ListViews
*/
private AdapterView.OnItemClickListener mDeviceClickListener
= new AdapterView.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);
/**
* 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();
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import com.mcn.bluetoothchat.R;
import com.mcn.bluetoothchat.model.ChatMessage;
import java.util.ArrayList;
import java.util.List;
/**
* Created by amit on 30/3/17.
*/
@Override
public void add(ChatMessage object) {
chatMessageList.add(object);
super.add(object);
}
package com.mcn.bluetoothchat.model;
/**
* Created by amit on 30/3/17.
*/
package com.mcn.bluetoothchat.services;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import com.mcn.bluetoothchat.utils.Constants;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;
/**
* Created by amit on 30/3/17.
*/
public class BluetoothChatService {
// Debugging
private static final String TAG = "BluetoothChatService";
// Member fields
private final BluetoothAdapter mAdapter;
private final Handler mHandler;
private AcceptThread mSecureAcceptThread;
private AcceptThread mInsecureAcceptThread;
private ConnectThread mConnectThread;
private ConnectedThread mConnectedThread;
private int mState;
private int mNewState;
/**
* 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;
mNewState = mState;
mHandler = handler;
}
/**
* Update UI title according to the current state of the chat connection
*/
private synchronized void updateUserInterfaceTitle() {
mState = getState();
mNewState = mState;
// Give the new state to the Handler so the UI Activity can update
mHandler.obtainMessage(Constants.MESSAGE_STATE_CHANGE, mNewState,
-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() {
/**
* Start the ConnectThread to initiate a connection to a remote device.
*
* @param device The BluetoothDevice to connect
* @param secure Socket Security type - Secure (true) , Insecure (false)
*/
public synchronized void connect(BluetoothDevice device, boolean secure) {
// Cancel any thread attempting to make a connection
if (mState == STATE_CONNECTING) {
if (mConnectThread != null) {
mConnectThread.cancel();
mConnectThread = null;
}
}
/**
* 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, final String socketType) {
// Cancel the accept thread because we only want to connect to one device
if (mSecureAcceptThread != null) {
mSecureAcceptThread.cancel();
mSecureAcceptThread = null;
}
if (mInsecureAcceptThread != null) {
mInsecureAcceptThread.cancel();
mInsecureAcceptThread = null;
}
/**
* Stop all threads
*/
public synchronized void stop() {
if (mConnectThread != null) {
mConnectThread.cancel();
mConnectThread = null;
}
if (mConnectedThread != null) {
mConnectedThread.cancel();
mConnectedThread = null;
}
if (mSecureAcceptThread != null) {
mSecureAcceptThread.cancel();
mSecureAcceptThread = null;
}
if (mInsecureAcceptThread != null) {
mInsecureAcceptThread.cancel();
mInsecureAcceptThread = null;
}
mState = STATE_NONE;
// Update UI title
updateUserInterfaceTitle();
}
/**
* 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;
// 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() {
// Send a failure message back to the Activity
Message msg = mHandler.obtainMessage(Constants.MESSAGE_TOAST);
Bundle bundle = new Bundle();
bundle.putString(Constants.TOAST, "Unable to connect device");
msg.setData(bundle);
mHandler.sendMessage(msg);
mState = STATE_NONE;
// Update UI title
updateUserInterfaceTitle();
/**
* Indicate that the connection was lost and notify the UI Activity.
*/
private void connectionLost() {
// Send a failure message back to the Activity
Message msg = mHandler.obtainMessage(Constants.MESSAGE_TOAST);
Bundle bundle = new Bundle();
bundle.putString(Constants.TOAST, "Device connection was lost");
msg.setData(bundle);
mHandler.sendMessage(msg);
mState = STATE_NONE;
// Update UI title
updateUserInterfaceTitle();
/**
* 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;
private String mSocketType;
}
mmServerSocket = tmp;
mState = STATE_LISTEN;
}
}
}
}
/**
* 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;
private String mSocketType;
/**
* 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;
mmInStream = tmpIn;
mmOutStream = tmpOut;
mState = STATE_CONNECTED;
}
/**
* Write to the connected OutStream.
*
* @param buffer The bytes to write
*/
public void write(byte[] buffer) {
try {
mmOutStream.write(buffer);
/*
* Copyright (C) 2014 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.mcn.bluetoothchat.utils;
import com.mcn.bluetoothchat.services.BluetoothChatService;
/**
* Defines several constants used between {@link BluetoothChatService} and the UI.
*/
public interface Constants {
}
package com.mcn.bluetoothchat;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
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;
import com.mcn.bluetoothchat.activity.DeviceListActivity;
import com.mcn.bluetoothchat.services.BluetoothChatService;
import com.mcn.bluetoothchat.utils.Constants;
// Layout Views
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
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
@Override
protected void onStart() {
super.onStart();
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 void onDestroy() {
super.onDestroy();
if (mChatService != null) {
mChatService.stop();
}
}
@Override
public void onResume() {
super.onResume();
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();
}
}
}
/**
* Set up the UI and background operations for chat.
*/
private void setupChat() {
// Initialize the array adapter for the conversation thread
mConversationArrayAdapter = new ArrayAdapter<String>(this, R.layout.message);
mConversationView.setAdapter(mConversationArrayAdapter);
// Initialize the compose field with a listener for the return key
mOutEditText.setOnEditorActionListener(mWriteListener);
// Initialize the send button with a listener that for click events
mSendButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Send a message using content of the edit text widget
}
});
// Initialize the BluetoothChatService to perform bluetooth connections
mChatService = new BluetoothChatService(this, mHandler);
/**
* Makes this device discoverable for 300 seconds (5 minutes).
*/
private void ensureDiscoverable() {
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.
*/
private void sendMessage(String message) {
// Check that we're actually connected before trying anything
if (mChatService.getState() != BluetoothChatService.STATE_CONNECTED) {
Toast.makeText(this, getString(R.string.not_connected),
Toast.LENGTH_SHORT).show();
return;
}
// 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);
}
return true;
}
};
/**
* Updates the status on the action bar.
*
* @param resId a string resource ID
*/
private void setStatus(int resId) {
/**
* Updates the status on the action bar.
*
* @param subTitle status
*/
private void setStatus(CharSequence subTitle) {
/**
* 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 Constants.MESSAGE_STATE_CHANGE:
switch (msg.arg1) {
case BluetoothChatService.STATE_CONNECTED:
setStatus(getString(R.string.title_connected_to, mConnectedDeviceName));
mConversationArrayAdapter.clear();
break;
case BluetoothChatService.STATE_CONNECTING:
setStatus(R.string.title_connecting);
break;
case BluetoothChatService.STATE_LISTEN:
case BluetoothChatService.STATE_NONE:
setStatus(R.string.title_not_connected);
break;
}
break;
case Constants.MESSAGE_WRITE:
byte[] writeBuf = (byte[]) msg.obj;
// construct a string from the buffer
String writeMessage = new String(writeBuf);
mConversationArrayAdapter.add("Me: " + writeMessage);
break;
case Constants.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 Constants.MESSAGE_DEVICE_NAME:
// save the connected device's name
mConnectedDeviceName = msg.getData().getString(Constants.DEVICE_NAME);
break;
case Constants.MESSAGE_TOAST:
Toast.makeText(MainActivity.this, msg.getData().getString(Constants.TOAST),
Toast.LENGTH_SHORT).show();
break;
}
}
};
Toast.makeText(this, R.string.bt_not_enabled_leaving,
Toast.LENGTH_SHORT).show();
finish();
}
}
}
/**
* Establish connection with other device
*
* @param data An {@link Intent} with {@link
DeviceListActivity#EXTRA_DEVICE_ADDRESS} extra.
* @param secure Socket Security type - Secure (true) , Insecure (false)
*/
private void connectDevice(Intent data, boolean secure) {
// 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, secure);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.bluetooth_chat, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.secure_connect_scan: {
// Launch the DeviceListActivity to see devices and do scan
Intent serverIntent = new Intent(this, DeviceListActivity.class);
startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE_SECURE);
return true;
}
case R.id.insecure_connect_scan: {
// Launch the DeviceListActivity to see devices and do scan
Intent serverIntent = new Intent(this, DeviceListActivity.class);
startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE_INSECURE);
return true;
}
case R.id.discoverable: {
// Ensure this device is discoverable by others
ensureDiscoverable();
return true;
}
}
return false;
}
package com.mcn.bluetoothchat;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* Instrumentation test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() throws Exception {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("com.mcn.bluetoothchat", appContext.getPackageName());
}
}
package com.mcn.bluetoothchat;
import org.junit.Test;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
}
xml coding
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="@+id/title_paired_devices"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#666"
android:paddingLeft="5dp"
android:text="@string/title_paired_devices"
android:textColor="#fff"
android:visibility="gone" />
<ListView
android:id="@+id/paired_devices"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:stackFromBottom="true" />
<TextView
android:id="@+id/title_new_devices"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#666"
android:paddingLeft="5dp"
android:text="@string/title_other_devices"
android:textColor="#fff"
android:visibility="gone" />
<ListView
android:id="@+id/new_devices"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="2"
android:stackFromBottom="true" />
<Button
android:id="@+id/button_scan"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/button_scan" />
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ListView
android:id="@+id/in"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:stackFromBottom="true"
android:dividerHeight="0dp"
android:transcriptMode="alwaysScroll" />
<LinearLayout
android:layout_width="match_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>
</LinearLayout>
<resources>
</resources>
<resources>
</resources>
android {
compileSdkVersion 25
buildToolsVersion "25.0.2"
defaultConfig {
applicationId "com.mcn.bluetoothchat"
minSdkVersion 15
targetSdkVersion 25
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:25.3.0'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
testCompile 'junit:junit:4.12'
}
7-Testing and Implementation
SOFTWARE TESTING
Testing Objectives:-
Testing begins at the module level and works outward towards the
integration of the entire computer based system.
Different testing techniques are appropriate at different point of time.
Testing is conducted by the developer of the software and independent
test group (ITG).
Testing and debugging are different activities, but debugging must be
accommodated in any testing strategy.
Unit testing begins at the vortex of the spiral and concentrate on each unit of
the software as implemented in the source code. As we know that initially
test focus on each module individually, ensuring that it function properly as a
unit. It makes heavy use of white box Testing.
Integration testing where the focus is on the design and construction of the
software architecture.
System tests where the software and other system element are tested as a
whole.
Debugging
This app allows you to create your own chat room that people around can
join in via Bluetooth connection. Bluetooth chat is a messaging application
that uses Bluetooth as the connection method, Bluetooth does not require
Internet connection, and this method of messaging has no cost.
It gives simple approaches to deal with the Bluetooth connector of the
nearby gadget and to send control keys, interchange keys, capacity keys and
other uncommon keys.
In future, it is possible to add more fields for notifications and extend scope
to the whole country.
9-References
Android Tutorial
Sites https://developer.android.com/develop/index.html
http://www.vogella.com/tutorials/android.html
10-Appendix