Date post: | 15-Jan-2015 |
Category: |
Education |
Upload: | karumanchirk |
View: | 1,244 times |
Download: | 4 times |
1
Instant Bluetooth Messenger v1.0
Developer Team
Rajesh Kumar Karumanchi
Lakshmipathi Sastry Ch
OSW Nicks:
BrOkEN@!
PothuRAJU
2
Abstract
This work contains research in usage of Bluetooth applications for mobile device. In
addition a detailed exploration of Bluetooth and J2ME the work consist of design and
implementation of sample application using Bluetooth transfer called Instant Bluetooth
Messenger (IBM).This application servers as a communication platform, enabling two
BT clients to connect their mobile phones and send each other text messages.
3
Contents
Abstract
1. Instant Bluetooth Messenger
1.1 What is IBM?
1.2 Messaging with IBM
1.3 Supported Devices
1.3.1 Device Configuration
1.3.2 Device Profile
2. Bluetooth®
2.1 What is Bluetooth®
?
2.2 History of Bluetooth®
Technology
2.3 Using Bluetooth®
2.4 Bluetooth Protocol Stack
2.5 Bluetooth Profiles
2.6 Comparison to other Technology: Why not others?
3. Java 2: Micro Edition (J2ME™
)
3.1 Configuration and Profile
3.2 Supported Packages and Limitations
3.3 Other Sources of Information
4. Bluetooth®
& J2ME™
4.1 Java APIs for Bluetooth-JABWT
4.2 Supports for Bluetooth (JSR-82) in Mobile Platform
5. Development & Description of Application
5.1 Proposal Draft & Later Changes
5.1.1 Use of Application
5.1.2 Life Cycle of Application
5.2 Description of Application Control
5.2.1 Connection Establishment
5.2.2 Messaging
5.3 Detailed Look in Application Development
5.4 MIDlets Used
6. Conclusion
7. Future Work
8. List of Literature
4
1 Instant Bluetooth Messenger
Today, 70% of people in the world use Handheld Devices like Mobiles,
PDAs & etc. Two people with in short Distances can communicate with this application
and they can chat with each other without using SMS or MMS & without Spending
money for communication.
1.1 What is IBM?
IBM is the next generation instant messenger for mobile phones. Fun, fast,
and easy to use, IBM utilizes Bluetooth technology to search for friends online and chat
with them exactly the same way as you would do with MSN/Windows Live Messenger,
ICQ, Yahoo AIM, or other instant messaging programs on your computer.
1.2 Messaging with IBM
Most instant messaging programs on mobile phones use either the SMS or
the Internet service provided by a cellular network to connect to the messaging services,
and this costs money. IBMV1.0 uses Bluetooth technology to communicate directly with
another mobile phone running IBMV1.0 bypasses the cellular network, and therefore does
not cost any money at all.
1.3 Supported Devices
Any Small Computing Device which supports JAVA (Mobiles & PDAs)
and JABWT with
1.3.1 Device Configuration:
• CLDC 1.1 & Above (Connected Limited Device configuration).
• 16-bit (or) 32-bit.
• Memory: should have between 160KB and 512KB.
1.3.2 Device Profile:
• MIDP 2.0 & Above (Mobile Information Device Profile, JSR-37 & 118).
5
2 Bluetooth®
2.1 What is Bluetooth®?
Bluetooth® is a Wireless Technology for Communication of Voice and
Data, based on Short-range Radio Standard. Designed for OTA -Over the Air
communication to eliminate the cables connected among devices which are at small
distances. The main task was to move away from electronic equipment cables, which are
interconnected among them. After the discovery of its potential, began to rapidly increase
its popularity, today as integral part of any better equipped mobile phone.
Fig: Several commonly used Bluetooth Devices.
2.2 History of Bluetooth® Technology
Already in 1994, Ericsson began to address the design technology that
would allow wireless connection of mobile devices and their accessories. The main
requirements were low cost components, low power consumption and dimensions of the
device. Soon to be added Ericsson, Intel, IBM, Nokia and Toshiba in 1998, together
creating a group of research Bluetooth wireless technology (Bluetooth Special Interest
Group - SIG), which has the task specify in detail the standard Bluetooth. In July 1999
the Bluetooth SIG publishes Bluetooth specification version 1.0.
Today, the current specification v1.2 and is already working on v2.0
(Specifications are available at [11]). Bluetooth Special Interest Group has around 2 000
6
members. All information about Bluetooth technology is available on the web site [10].
There can also find details of the Bluetooth SIG group, namely the reference
http://www.bluetooth.com/Bluetooth/SIG
2.3 Using Bluetooth®
Bluetooth technology has today countless different uses in many
industries. The following list indicates some areas where the Bluetooth technology no
longer applies.
• Data communication between two identical devices (Mobile phones, PDA
devices, laptops, etc.)
• Data communication between two different devices (PC and mobile phone, PC
and PDA, mobile phone and printer, etc.)
• Voice transmission between mobile phone and hands free set.
• Connection to PC peripherals (keyboard, mouse, headset, printer).
• Ad-hoc local area network between computers.
• Remote control devices in the home (PC, etc.).
Other uses of Bluetooth can specify the programmer himself. And simply
by typing application working with this driver and install it in appropriately equipped
facilities. Alternatively they may also offer equipment itself to suit the exact
requirements of its application.
2.4 Bluetooth Protocol Stack
Core Bluetooth specification is called "Bluetooth protocol stack, which
defines how a technology works. Bluetooth divides the individual layers, much like ISO
OSI model of computer networks. His chart shows the Figure 4, the lower layer from
higher separates the so-called HCI (Host Controller Interface). Radio is the lowest layer,
which takes care of modulation and demodulation signals and describes the physical
requirements for Bluetooth transmitter and receiver of a particular device. Baseband /
Link Controller layer handles format data into a form suitable for transmission by air and
synchronization connections. Link Layer manager will establish and maintain
7
connections between devices. Like in computer networks, here we distinguish by type of
communication connection is established.
There are two types of communication:
• Synchronous communication mergers - Synchronous, Connection-Oriented SCO),
mainly used for voice communication (e.g. headset profile)
• Asynchronous communication without joining - Asynchronous, Connectionless
(ACL) suited mainly for data communication
HCI (Host Controller Interface) is responsible for co-operation of higher
layers with lower layers (Radio, Baseband, Link manager). The higher layers such as
L2CAP (Logical Link Control and Adaptation Protocol), which is responsible for
encapsulating packets into a format suitable for the lower layer connection multiplexing,
so that could be used more applications, etc. SDP (Service Discovery Protocol) formulate
action in offering a search of Bluetooth devices. RFCOMM layer allows emulating a
serial connection cable, with all the specifics of the standard RS-232. So they can via
Bluetooth communication applications designed for serial communication port.
8
2.5 Bluetooth Profiles
For a device to use the Bluetooth technology must be able to interpret
individual Bluetooth profiles. They are there to prevent any incompatibility was
eliminated developed programs for Bluetooth devices of different manufacturers. Each
profile represents a different application, or any other task.
Its specification must include:
• Dependencies on other profiles
• The proposed user interface formats
• Parts Bluetooth protocol stack used by the profile
9
A Bluetooth device can support one or more profiles. The four “basic”
profiles are the Generic Access Profile (GAP), the Serial Port Profile(SPP), the
Service Discovery Application Profile (SDAP), and the Generic Object Exchange Profile
(GOEP).
� The GAP is the basis of all other profiles. Strictly speaking, all profiles are based
on the GAP. GAP defines the generic procedures related to establishing
connections between two devices, including the discovery of Bluetooth devices,
link management and configuration, and Procedures related to use of different
security levels.
� The SDAP describes the fundamental operations necessary for service discovery.
This profile defines the protocols and procedures to be used by applications to
locate services in other Bluetooth enabled devices.
� The SPP defines the requirements for Bluetooth devices necessary for setting up
emulated serial cable connections using RFCOMM between two peer devices.
SPP directly maps to the RFCOMM protocol and enables legacy applications
using Bluetooth wireless technology as a cable replacement.
� The GOEP is an abstract profile on which concrete usage case Profiles can
be built. These are profiles using OBEX. The profile defines all elements
necessary for support of the OBEX usage models (e.g., file transfer,
synchronization, or object push).
The basic profiles—GAP; SDAP, SPP, and GOEP—also are known as
transport profiles, Upon which other profiles, known as application profiles, can be built.
2.6 Comparison to other Technology: Why not others?
There are many short-range wireless standards, but the three main ones are
Infrared from the Infrared Data Association® (IrDA®), Bluetooth wireless technology,
and wireless local area network (WLAN). WLAN is also known as IEEE 802.11, and it
comes in three main variants, 802.11b and 802.11g, which operate at 2.4 gigahertz
(GHz), and 802.11a, which operates at 5 GHz. The IrDA created a wireless
communications system that makes use of infrared light. Whereas RF communication
10
can penetrate many objects, IrDA is limited to line of sight. Both 802.11b and
Bluetooth wireless technologies communicate in the 2.4-GHz RF band but are aimed
at different market segments. The 802.11b technology has a longer range but consumes
substantially more power than Bluetooth wireless technology. The 802.11 variant is
primarily for data. The only protocol for supporting voice is Voice over Internet Protocol
(VoIP).
11
3 Java 2: Micro Edition (J2ME™)
Java 2 Micro Edition (J2ME for short) is one of the three editions of Java.
J2SE and J2EE are to create applications for personal computers and Servers
respectively. Java Micro Edition objective is to provide programmers development
environment for creating applications designed to run on small portable devices such as
mobile phones, pagers, PDA personal assistants, navigation systems, etc... Advantages
J2ME are similar to traditional Java is portability code, object-oriented programming,
etc.. J2ME is adapted so that it cannot problems to work on small portable devices.
Restrictions such devices are For example: poor imaging capabilities (small display with
low resolution and low color depth), a complicated method of control (no or only
numeric keypad), a small memory, the problem of data storage (small fixed memory),
low computing power (incomparable as a personal computer). These features had to be
specification J2ME adjusted, so it was necessary to restrict only some packages from
source Java specification. On the other hand, were for the needs of mobile devices
added packages new classes and methods supporting new technologies and possibilities
of modern equipment.
12
3.1 Configuration and Profile
Configurations are composed of a Java virtual machine and a minimal set
of class libraries. The Java virtual machine usually runs on top of a host operating system
that is part of the target device’s system software.
Currently, there are two J2ME configurations:
1. Connected, Limited Device Configuration (CLDC)
2. Connected Device Configuration (CDC)
A CLDC implementation generally includes a Kilobyte Virtual Machine
(KVM). The KVM is specially designed for memory constrained devices. CDC includes
a virtual machine that conforms fully to the Java Virtual Machine Specification.
13
Configurations do not usually provide a complete solution. Profiles add
the functionality and the APIs required to complete a fully functional runtime
environment for a class of devices. Configurations must be combined with Profiles
that define the higher-level APIs for providing the capabilities for a specific market or
industry.Basic Profiles are;
1. Mobile Information Device Profile (MIDP) - appeared first and
was designed for mobile phones, pagers and PDAs, together with
the CLDC constitutes an excellent base for creating complex
applications. Today, the mobile most used (current version
supports the new features phones bearing MIDP 2.0 is
implemented in most of the newly presented mobiles).
2. Information Module Profile (IMP) - is based on MIDP, intended
for so-called embedded Equipment (serving machines, industrial
applications, security systems and similar devices with little or no
display and limited network connection),contains user interface
API (without the GUI)
3. Foundation Profile (FP) - is the application of such devices
without the UI
4. Personal Basis Profile(PBP) - Extended Foundation profile,
support for GUI
5. Staff Profile (PP) - often used in game consoles, communicators,
promoting AWT and Applets.
3.2 Supported Packages and Limitations
Since the application developed using Bluetooth Messenger for MIDP
profile, Packages and classes are addressed only to this Profile.
Configuration CLDC supports the selected class from the standard
Java libraries
� java.util
� java.lang
� java.io
� javax.microedition.io
14
Profile configuration CLDC MIDP enriches the following libraries:
� javax.microedition.rms (for storage)
� javax.microedition.midlet
� javax.microedition.io (extending a class Http Connection)
� javax.microedition.lcdui (control interface)
However, the MIDP profile brings with it several limitations, such as:
o screen size minimum 96 x 54 pixels
o presence of button or touch the keyboard
o at least 128 kilobytes of memory for permanent MIDP components
o at least 8 kilobytes of memory for permanent storage
o at least 32kB of memory to run the program (heap VM)
3.3 Other Sources of Information
All documentation for J2ME, i.e. all the profiles and configurations, it is
possible found on the web site. Materials for J2ME is can be found in the developer
section of Sun's website as well as on some sites of manufacturers of mobile devices.
Useful Links:
http://java.sun.com/javame/downloads/index.jsp
http://java.sun.com/javame/technology/index.jsp
15
4 Bluetooth® & J2ME™
Standard APIs in the Java programming language are defined though the
Java Community Process (JCP). The JCP coordinates the evolution of the Java
programming language. Each new API is developed as a Java Specification Request
(JSR). All J2ME configurations, Profiles, and optional packages are defined as JSRs. The
expert groups that defined JABWT consisted of 18 companies and three individuals. The
API was defined as an optional package for J2ME devices based on CLDC.
4.1 Java APIs for Bluetooth-JABWT
JABWT defines two basic classes:
• javax.bluetooth
• javax.obex
Both these classes are dependent on the class javax.microedition.io, serving
input Output application events. Some mobile devices support only javax.bluetooth class,
while the methods javax.obex on them is not possible to work (typically mobile phones
Nokia).
16
Applications that use Bluetooth has in most cases very similar scenario to
summarize the following points:
1. Bluetooth stack initialization (setting the parameters of the Bluetooth
device, run Bluetooth)
2. search facilities that are within range
3. search services on the devices found
4. establish a connection with the suitable equipment
5. perform input / output operations
6. close all open connections and streams
4.2 Support for Bluetooth (JSR-82) in Mobile Platform
Java API enables applications to run on different types of hardware,
operating systems, and classes of device. In addition to portability, the Java language
provides several other benefits.
o Rapid development of applications because of the better
abstractions and high-level programming constructs provided by
an object-oriented programming language.
o Ability to dynamically expand a program’s functionality during
execution by loading classes at runtime.
o Standards with better user interfaces and that support sophisticated
user interaction.
17
5 Development & Description of Application
5.1 Proposal Draft & Later Changes
IBM is the next generation instant messenger for mobile phones. Fun, fast,
and easy to use, IBM utilizes Bluetooth technology to search for friends online and chat
with them exactly the same way as you would do with MSN/Windows Live Messenger,
ICQ, Yahoo AIM, or other instant messaging programs on your computer. Most instant
messaging programs on mobile phones use either the SMS or the Internet service
provided by a cellular network to connect to the messaging services, and this costs
money. IBMV1.0 uses Bluetooth technology to communicate directly with another mobile
phone running IBMV1.0 bypasses the cellular network, and therefore does not cost any
money at all.
Communication via IBM
Fig: Communication between two IBM Clients
5.1.1. Use of Application
IBM is designed for text communication over short distances. Is
particularly suitable in cases where the parties are close together but not together directly
speak. The consideration comes as a situation where you need to consult a problem but it
is not possible to cancel near interview (lecture, school teaching, conference, etc.).
Interesting is certainly the issue of communication of people in different rooms (in the
secondary offices in the work, the dorm rooms, etc.), but here is the biggest setback small
range Bluetooth enabled phones. Use IBM application could even the hearing-impaired
people. Those could be used instead of pencil and paper, communicating a person who
18
Chat/Commun
icate
End
Application
Launch Server
Application
Accept the
Connections
Join Server
Application
Search
Servers
uses sign language. On second thought, it is possible to come to many potential uses of
this application.
5.1.2 Life Cycle of the Application
Server Not Found
Server Found
End
5.2 Description of Application Control
Below figures shows how the application control is followed throughout
the development of Application. Later the connection establishment, accepting the client
connections and Messaging are explained.
Start
19
Main Tasks are:
� Establish Connection
� Messaging
5.2.1 Connection Establishment:
5.2.2 Messaging:
5.3 Detailed Look in Application Development
Fig: Lay Out of the Application Description
User interface was chosen so that the application was compatible with the
greatest number of facilities.
the blunt, simple, intuitive and functional.
drawing connections. Individual images show the screen (display)
of the contents of the screen and contextual button labels.
between screens. Each event (search server, a server) is
button. Once a participant chooses a nickname, is to search
create a party. Following the successful merger of two parties
screen chat (see below).
Detailed Look in Application Development
Fig: Lay Out of the Application Description
User interface was chosen so that the application was compatible with the
umber of facilities. Application will therefore be free of any graphic elements,
the blunt, simple, intuitive and functional. Figure shows a sample graphic interface for
Individual images show the screen (display) equipment
of the contents of the screen and contextual button labels. Arrows show transitions
Each event (search server, a server) is can cancel the appropriate
Once a participant chooses a nickname, is to search server. If not found,
Following the successful merger of two parties is put on the display
20
User interface was chosen so that the application was compatible with the
Application will therefore be free of any graphic elements,
interface for
quipment and consist
transitions
an cancel the appropriate
If not found, it can
is put on the display
21
22
Below Figure shows the contrary, each screen while chatting. The main
displays window-chat messages and fields for entering text. Under one of the buttons are
contextual hide menu containing several items (send messages, change status, end
applications clear the screen). After pressing the button to change the status window will
open and allow configuration status of the participant (his current disposition chat).
23
5.4 MIDlets Used
Packages:
bluetooth.client.java
package bluetooth;
import javax.bluetooth.*;
import javax.microedition.io.Connector;
import main.ConnectionStruct;
import main.Main;
public class Client implements Runnable {
private ServiceRecord service;
private ConnectionStruct conn;
private int state;
private String message;
private String friend;
private String connectionURL;
public Client(ServiceRecord servicerecord, String s, boolean flag) {
state = 0;
if (flag) {
try {
service = servicerecord;
friend = s;
connectionURL = servicerecord.getConnectionURL(2, false);
conn = new ConnectionStruct();
L2CAPConnection l2capconnection = (L2CAPConnection)
Connector.open(connectionURL);
conn.setConnection(l2capconnection);
DataElement dataelement = servicerecord.getAttributeValue(256);
String s1 = (String) dataelement.getValue();
s1 = s1.substring(s1.indexOf("_") + 1);
Main.getServer().setDis(s1, conn);
Main.getServer().talk(s1);
conn.write(Server.serverName);
} catch (Exception exception) {
Bluetooth
Main
UI
24
Main.getChooseDeviceForm().getChatForm(s).addMsg("Maybe this person
isn't available anymore", s);
Main.getChooseDeviceForm().getChatForm(s).setFriendLeft();
Main.getChooseDeviceForm().getChatForm(s).removeCommandChat();
}
}
}
public void talk(String s) {
System.out.println("mesaj->" + s);
message = s;
Thread thread = new Thread(this);
thread.setPriority(2);
thread.start();
}
public void run() {
communicate();
}
public void communicate() {
if (message != null && !message.trim().equals("")) {
System.out.println("aici:" + message);
if (conn != null) {
conn.write(message);
} else {
System.out.println("NULL");
}
}
}
public void closeInOut() {
conn.closeINOUT();
}
public void setCommunicator(L2CAPConnection l2capconnection) {
conn = new ConnectionStruct();
conn.setConnection(l2capconnection);
}
}
25
bluetooth.Discover.java
package bluetooth;
import java.util.*;
import javax.bluetooth.*;
import main.Main;
import ui.ChooseDevice;
public class Discovery extends Thread implements DiscoveryListener {
private LocalDevice local;
private DiscoveryAgent agent;
private static Vector devices;
private static Hashtable serviceTable;
private static String serviceFound;
private static ServiceRecord serviceRecFound;
public static final String RFCOMM_UUID = "86b4d249fb8844d6a756ec265dd1f6a3";
private boolean inquiry;
private int searchService;
private boolean mIBM;
private boolean canceled;
private int index;
private Waiter waiter;
private static Vector v = new Vector();
public Discovery() {
inquiry = false;
searchService = 0;
canceled = true;
index = 0;
waiter = new Waiter();
mIBM = true;
waiter.setPriority(2);
waiter.start();
}
public synchronized void run() {
do {
if (!mIBM) {
break;
}
try {
wait();
} catch (InterruptedException interruptedexception) {
}
26
if (mIBM) {
System.out.println("porneste iar ----- ");
initDiscovery();
doDiscoveryDevices();
}
} while (true);
}
public synchronized void go() {
while (!canceled);
notify();
}
public void cancel() {
endDiscovery();
}
public synchronized void stop() {
while (!canceled) {
mIBM = false;
waiter.stop();
notify();
}
}
public void initDiscovery() {
Main.getChooseDeviceForm().rearangeElements(ChooseDevice.tick);
serviceTable = new Hashtable();
devices = new Vector();
canceled = false;
serviceFound = null;
serviceRecFound = null;
}
public void deviceDiscovered(RemoteDevice remotedevice, DeviceClass deviceclass)
{
devices.addElement(remotedevice);
}
public void inquiryCompleted(int i) {
inquiry = false;
switch (i) {
default:
break;
case 0: // '\0'
27
synchronized (devices) {
if (devices.size() > 0) {
index = 0;
RemoteDevice remotedevice = (RemoteDevice) devices.elementAt(0);
System.out.println("un remote device - inquiry completed " +
devices.size());
waiter.go(remotedevice);
} else {
Main.getChooseDeviceForm().populateAndSetActive();
index = 0;
canceled = true;
}
}
break;
case 7: // '\007'
canceled = true;
break;
case 5: // '\005'
canceled = true;
break;
}
}
public void serviceSearchCompleted(int i, int j) {
searchService = 0;
System.out.println("devices.size() -> " + index + " " + devices.size());
synchronized (devices) {
if (devices != null && index < devices.size() - 1) {
if (serviceFound != null && serviceRecFound != null) {
Main.getChooseDeviceForm().newDevice(serviceFound, serviceRecFound);
}
index++;
RemoteDevice remotedevice = (RemoteDevice) devices.elementAt(index);
waiter.go(remotedevice);
} else {
if (serviceFound != null && serviceRecFound != null) {
Main.getChooseDeviceForm().newDevice(serviceFound, serviceRecFound);
}
Main.getChooseDeviceForm().populateAndSetActive();
index = 0;
canceled = true;
}
}
switch (j) {
28
case 1: // '\001'
System.out.println("everything is completed");
break;
case 6: // '\006'
System.out.println("not reachable");
break;
case 3: // '\003'
System.out.println("search err");
break;
case 4: // '\004'
System.out.println("no records");
break;
case 2: // '\002'
System.out.println("search canceled");
break;
}
}
public void servicesDiscovered(int i, ServiceRecord aservicerecord[]) {
System.out.println("services discovered");
boolean flag = false;
if (aservicerecord != null) {
for (int j = 0; j < aservicerecord.length; j++) {
if (aservicerecord[j] == null) {
continue;
}
DataElement dataelement = aservicerecord[j].getAttributeValue(256);
String s = (String) dataelement.getValue();
int k = s.indexOf(Server.separatorCharacter);
if (s != null && k != -1 && s.substring(0, k).equals(Server.serviceName)) {
System.out.println("put aici :D ");
serviceTable.put(s.substring(k + 1), aservicerecord[j]);
serviceFound = s.substring(k + 1);
serviceRecFound = aservicerecord[j];
flag = true;
}
}
}
if (!flag) {
serviceFound = null;
serviceRecFound = null;
29
}
}
private void doDiscoveryDevices() {
try {
local = LocalDevice.getLocalDevice();
} catch (BluetoothStateException bluetoothstateexception) {
bluetoothstateexception.printStackTrace();
}
agent = local.getDiscoveryAgent();
try {
inquiry = agent.startInquiry(0x9e8b33, this);
} catch (BluetoothStateException bluetoothstateexception1) {
}
}
public void doServiceSearch(RemoteDevice remotedevice) {
UUID auuid[] = new UUID[1];
auuid[0] = new UUID("86b4d249fb8844d6a756ec265dd1f6a3", false);
int ai[] = {
256
};
try {
searchService = agent.searchServices(ai, auuid, remotedevice, this);
} catch (BluetoothStateException bluetoothstateexception) {
bluetoothstateexception.printStackTrace();
} catch (Exception exception) {
}
}
public static Vector getDevices() {
v = new Vector();
for (Enumeration enumeration = serviceTable.keys();
enumeration.hasMoreElements(); v.addElement(enumeration.nextElement()));
return v;
}
public static ServiceRecord getSelected(int i) {
boolean flag = false;
try {
ServiceRecord servicerecord = (ServiceRecord) serviceTable.get(v.elementAt(i));
return servicerecord;
} catch (NoSuchElementException nosuchelementexception) {
return null;
}
30
}
private void endDiscovery() {
if (inquiry) {
try {
inquiry = !agent.cancelInquiry(this);
if (inquiry) {
System.out.println("Could not stop");
}
} catch (Exception exception) {
System.out.println(exception.getMessage() + " endDiscovery ->
cancelInquiry");
exception.printStackTrace();
}
}
if (searchService != 0) {
try {
agent.cancelServiceSearch(searchService);
} catch (Exception exception1) {
System.out.println(exception1.getMessage() + " endDiscovery ->
searchService");
exception1.printStackTrace();
}
searchService = 0;
}
}
}
bluetooth.Server.java
package bluetooth;
import java.io.*;
import java.util.Enumeration;
import java.util.Hashtable;
import javax.bluetooth.*;
import javax.microedition.io.Connector;
import javax.microedition.lcdui.AlertType;
import main.ConnectionStruct;
import main.Main;
import ui.*;
public class Server implements Runnable {
31
private static LocalDevice local;
private static L2CAPConnectionNotifier noty;
private static L2CAPConnection connection;
private ConnectionStruct conn;
private static Hashtable allConns;
private static boolean finished = false;
private String connectionURL;
public static String serviceName = "IBM";
public static String serverName;
public static String separatorCharacter = "_";
private class InnerListener
implements Runnable {
public void startInnerListener(String s) {
friend = s;
Thread thread = new Thread(this);
thread.setPriority(2);
thread.start();
}
public void run() {
String s = "";
boolean flag = false;
ConnectionStruct connectionstruct = null;
if (Server.allConns.size() != 0 && Server.allConns.containsKey(friend)) {
connectionstruct = (ConnectionStruct) Server.allConns.get(friend);
}
if (connectionstruct != null && friend != null) {
do {
if (flag) {
break;
}
String s1;
if (connectionstruct != null) {
if ((s1 = connectionstruct.read()) != null) {
if (OptionsForm.alertSound.equals("true")) {
AlertType.INFO.playSound(Main.getDisplay());
}
if (OptionsForm.vibrate.equals("true")) {
Main.getDisplay().vibrate(800);
}
Main.getChooseDeviceForm().getChatForm(friend).addMsg(friend.substring(0,
friend.indexOf("_")) + ": " + s1.toString(), friend);
32
if (Main.getChooseDeviceForm().getChatForm(friend).isFormShown())
{
Main.getChooseDeviceForm().getChatForm(friend).scroll();
}
} else {
flag = true;
Main.getChooseDeviceForm().getChatForm(friend).addMsg("< " +
friend.substring(0, friend.indexOf("_")) + " left >", friend);
Main.getChooseDeviceForm().getChatForm(friend).removeCommandChat();
if (Main.getChooseDeviceForm().getChatForm(friend).isFormShown())
{
Main.getChooseDeviceForm().getChatForm(friend).scroll();
}
Main.getChooseDeviceForm().getChatForm(friend).setFriendLeft();
}
}
} while (true);
}
}
private String friend;
private InnerListener() {
}
}
public Server() {
}
public void setServer(String s) {
try {
local = LocalDevice.getLocalDevice();
local.setDiscoverable(0x9e8b33);
} catch (BluetoothStateException bluetoothstateexception) {
bluetoothstateexception.printStackTrace();
}
Server _tmp = this;
serverName = s + "_" + local.getBluetoothAddress();
connectionURL =
"btl2cap://localhost:86b4d249fb8844d6a756ec265dd1f6a3;name=" + serviceName +
separatorCharacter + serverName;
startServer();
}
public void startServer() {
finished = false;
33
allConns = new Hashtable();
Thread thread = new Thread(this);
thread.setPriority(2);
thread.start();
}
public void stopServer() {
try {
finished = true;
if (conn != null) {
conn.closeINOUT();
conn = null;
}
for (Enumeration enumeration = allConns.elements();
enumeration.hasMoreElements();
((ConnectionStruct) enumeration.nextElement()).closeINOUT()) {
allConns.clear();
allConns = null;
}
if (noty != null) {
noty.close();
noty = null;
}
System.gc();
} catch (IOException ioexception) {
} catch (Exception exception) {
}
Main.getInstance().exitApp();
}
public void run() {
try {
if (noty == null) {
noty = (L2CAPConnectionNotifier) Connector.open(connectionURL);
}
openConnection();
} catch (BluetoothStateException bluetoothstateexception) {
bluetoothstateexception.printStackTrace();
} catch (IOException ioexception) {
ioexception.printStackTrace();
} catch (NullPointerException nullpointerexception) {
nullpointerexception.printStackTrace();
} catch (ClassCastException classcastexception) {
System.out.println("@@@ CAST");
classcastexception.printStackTrace();
}
34
}
public void openConnection() {
do {
if (finished) {
break;
}
try {
noty = (L2CAPConnectionNotifier) Connector.open(connectionURL);
if (noty != null) {
connection = noty.acceptAndOpen();
}
if (connection != null && noty != null) {
conn = new ConnectionStruct();
conn.setConnection(connection);
String s = conn.read();
allConns.put(s, conn);
Main.getChooseDeviceForm().addToDisplayable(s);
Main.getClient(null, s, false).setCommunicator(connection);
talk(s);
}
} catch (InterruptedIOException interruptedioexception) {
System.out.println("Interrupted NOTY " +
interruptedioexception.getMessage());
interruptedioexception.printStackTrace();
} catch (IOException ioexception) {
System.out.println("CLOSE NOTY " + ioexception.getMessage());
ioexception.printStackTrace();
} catch (NullPointerException nullpointerexception) {
System.out.println("NULL POINTER EX. " +
nullpointerexception.getMessage());
nullpointerexception.printStackTrace();
}
} while (true);
}
public void talk(String s) {
InnerListener innerlistener = new InnerListener();
innerlistener.startInnerListener(s);
}
public String getConnectionURL() {
return connectionURL;
}
public void setDis(String s, ConnectionStruct connectionstruct) {
35
allConns.put(s, connectionstruct);
}
}
bluetooth.TimeRefresh.java
package bluetooth;
import java.util.TimerTask;
import main.Main;
public class TimerRefresh extends TimerTask {
public TimerRefresh(boolean flag) {
first = flag;
}
public void run() {
if (!first) {
Main.getDiscover().cancel();
}
Main.getDiscover().go();
}
public boolean first;
}
bluetooth.Waiter.java
package bluetooth;
import java.io.IOException;
import javax.bluetooth.RemoteDevice;
import main.Main;
public class Waiter extends Thread {
public Waiter() {
36
isWaiting = true;
}
public synchronized void run() {
do {
if (!isWaiting) {
break;
}
try {
wait();
} catch (InterruptedException interruptedexception) {
}
if (isWaiting) {
try {
System.out.println("friendly name :" +
remoteDevice.getFriendlyName(true));
} catch (IOException ioexception) {
ioexception.printStackTrace();
}
Main.getDiscover().doServiceSearch(remoteDevice);
}
} while (true);
}
public synchronized void go(RemoteDevice remotedevice) {
remoteDevice = remotedevice;
notify();
}
public synchronized void stop() {
isWaiting = false;
notify();
}
private boolean isWaiting;
private RemoteDevice remoteDevice;
}
Main.ConnectionStruct.java
package main;
import java.io.IOException;
import javax.bluetooth.L2CAPConnection;
public class ConnectionStruct {
37
public ConnectionStruct() {
connection = null;
}
public void setConnection(L2CAPConnection l2capconnection) {
connection = l2capconnection;
System.err.println("connection established");
}
public void write(String s) {
try {
if (connection != null) {
System.out.println("Diff de null");
}
if (s != null && !s.equals("")) {
byte abyte0[] = s.getBytes();
connection.send(abyte0);
} else {
System.out.println("NULL");
}
} catch (IOException ioexception) {
} catch (NullPointerException nullpointerexception) {
nullpointerexception.printStackTrace();
}
}
public String read() {
byte abyte0[];
abyte0 = null;
if (connection == null) {
System.out.println("conn nu e null");
}
try {
abyte0 = new byte[connection.getTransmitMTU()];
} catch (IOException ioexception) {
ioexception.printStackTrace();
}
byte abyte1[];
try {
int i = connection.receive(abyte0);
abyte1 = new byte[i];
System.arraycopy(abyte0, 0, abyte1, 0, i);
return new String(abyte1);
} catch (IOException iOException) {
38
System.out.println("conn E null");
return null;
}
}
public boolean isReady() {
try {
if (connection != null) {
/*break MISSING_BLOCK_LABEL_24;*/
return connection.ready();
} else {
return false;
}
} catch (IOException ex) {
ex.printStackTrace();
return false;
}
}
public void closeINOUT() {
try {
connection.close();
} catch (IOException ioexception) {
ioexception.printStackTrace();
}
connection = null;
}
public L2CAPConnection getConnection() {
return connection;
}
L2CAPConnection connection;
}
Main.main.java
package main;
import bluetooth.*;
import java.util.Hashtable;
import javax.bluetooth.ServiceRecord;
import javax.microedition.lcdui.Display;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;
import ui.*;
39
public class Main extends MIDlet {
public static boolean debug = true;
private static EnterName nickForm = new EnterName();
private static OptionsForm options = new OptionsForm();
private static About about = new About();
private static Display display;
private static Discovery discover;
private static Server server;
private static Hashtable client = new Hashtable();
private static Main instance;
private static ChooseDevice devicesForm;
public Main() {
instance = this;
display = Display.getDisplay(instance);
devicesForm = new ChooseDevice();
}
protected void destroyApp(boolean flag)
throws MIDletStateChangeException {
}
protected void pauseApp() {
}
protected void startApp()
throws MIDletStateChangeException {
showForm sf = new showForm();
sf.setPriority(1);
try {
showForm.sleep(5000);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
discover = new Discovery();
discover.setPriority(2);
discover.start();
nickForm.show();
}
public static Display getDisplay() {
return display;
}
40
public static Discovery getDiscover() {
if (discover == null) {
return discover = new Discovery();
} else {
return discover;
}
}
public static Server getServer() {
if (server == null) {
return server = new Server();
} else {
return server;
}
}
public static Main getInstance() {
return instance;
}
public static Client getClient(ServiceRecord servicerecord, String s, boolean flag) {
System.out.println("numePrieten:" + s);
if (!client.containsKey(s)) {
Client client1 = new Client(servicerecord, s, flag);
client.put(s, client1);
return client1;
} else {
return (Client) client.get(s);
}
}
public static boolean existsClient(String s) {
return client.containsKey(s);
}
public static void removeClient(String s) {
if (client.containsKey(s)) {
client.remove(s);
}
}
public static ChooseDevice getChooseDeviceForm() {
return devicesForm;
}
public static EnterName getNickForm() {
41
return nickForm;
}
public static OptionsForm getOptionsForm() {
return options;
}
public static About getAboutForm() {
return about;
}
public void exitApp() {
try {
destroyApp(false);
} catch (MIDletStateChangeException midletstatechangeexception) {
midletstatechangeexception.printStackTrace();
}
notifyDestroyed();
}
}
Main.showForm.java
package main;
import java.io.IOException;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Image;
import javax.microedition.lcdui.Ticker;
import org.netbeans.microedition.lcdui.SplashScreen;
public class showForm extends Thread {
private SplashScreen sp;
private Display display;
private static Ticker ticker = new Ticker("Developed BY Team-IBM(BrOkEN@!)");
private static Image image;
public showForm() {
super();
display = Main.getDisplay();
sp = new SplashScreen(display);
sp.setTicker(ticker);
try {
image = Image.createImage("/ibm.png");
} catch (IOException ex) {
ex.printStackTrace();
42
}
sp.setImage(image);
sp.setTimeout(5000);
Main.getDisplay().setCurrent(sp);
}
}
Ui.About.java
package ui;
import java.io.IOException;
import javax.microedition.lcdui.*;
import main.Main;
public class About implements CommandListener {
private Alert alert;
private static Ticker ticker;
private static Image image;
private Command okay;
public About() {
ticker = new Ticker("Developed BY Team-IBM(BrOkEN@!)");
okay = new Command("OK", Command.OK, 1);
try {
image = Image.createImage("/ibm.png");
} catch (IOException ex) {
ex.printStackTrace();
}
}
public Alert getAlert() {
if (alert == null) {
alert = new Alert("About", "Instant Bluetooth Messager v 1.0\n\nTerms &
Conditions :\nWe are not Responsible for any Kind of Damage Occured during the usage
of this Application.\nThis application is developed under Open Source Software Licence
(Can be distributed).\n\nContribute :\nApplication source can be downloaded from
http:\\\\www.karumanchi.co.cc\\projectibm\\.\n\nCredits :\nRajesh Kumar Karumanchi
(BrOkEN@!-Author)\nLakshmipathi Sastry (PothuRaju-Developer)", image,
AlertType.INFO);
alert.setTicker(ticker);
alert.addCommand(okay);
alert.setCommandListener(this);
alert.setTimeout(Alert.FOREVER);
// write post-init user code here
}
43
return alert;
}
public void setActive() {
Main.getDisplay().setCurrent(this.getAlert());
}
public void commandAction(Command c, Displayable d) {
if (c == okay) {
Main.getDisplay().setCurrent(Main.getChooseDeviceForm().getForma());
}
}
}
Ui.ChatForm.java
package ui;
import java.util.Vector;
import javax.bluetooth.ServiceRecord;
import javax.microedition.lcdui.*;
import main.Main;
public class ChatForm
implements CommandListener {
public ChatForm() {
form = new Form("Chat");
chat = new Command("Chat", 4, 0);
back = new Command("Back", 2, 0);
clear = new Command("Clear", 4, 1);
friendLeft = false;
}
public void buildBasic() {
form.addCommand(chat);
form.addCommand(back);
form.addCommand(clear);
form.setCommandListener(this);
textEnterForm = new WriteMessageForm(this);
}
private void repaint() {
Alert alert = new Alert("Updating display ...", null, null, AlertType.INFO);
alert.setTimeout(10);
Main.getDisplay().setCurrent(alert, Main.getDisplay().getCurrent());
}
public void setCurrent(final Vector completeNamesNicknames, final List forma) {
44
form.setTicker(null);
Main.getDisplay().setCurrent(form);
try {
form.notify();
} catch (Exception exception) {
}
scroll();
if (completeNamesNicknames != null && forma != null) {
Thread thread = new Thread() {
public void run() {
Main.getClient((ServiceRecord) completeNamesNicknames.elementAt(3 *
forma.getSelectedIndex() + 2), friend, true);
Main.getClient((ServiceRecord) completeNamesNicknames.elementAt(3 *
forma.getSelectedIndex() + 2), friend, true).talk("");
}
};
thread.start();
}
}
public Form getForm() {
return form;
}
public void scroll() {
form.append(new StringItem("", null));
Main.getDisplay().setCurrentItem(form.get(form.size() - 1));
}
public void setFriend(String s) {
friend = s;
textEnterForm.setFriend(friend);
}
public void addMsg(String s, String s1) {
StringItem stringitem = new StringItem("", null);
stringitem.setText(s + " \n");
form.append(stringitem);
if (!form.isShown() && s != null && !s.equals("")) {
if (Main.getChooseDeviceForm().getForma().isShown()) {
Main.getChooseDeviceForm().rearangeElements(new
Ticker(friend.substring(0, friend.indexOf("_")) + " wants to talk with you"));
} else {
Main.getDisplay().getCurrent().setTicker(new Ticker(friend.substring(0,
friend.indexOf("_")) + " wants to talk with you"));
45
}
Main.getChooseDeviceForm().addChatCommand();
Main.getChooseDeviceForm().addNewMessageIcon(s1);
}
}
public void removeCommandChat() {
form.removeCommand(chat);
}
public void commandAction(Command command, Displayable displayable) {
if (command == chat) {
textEnterForm.setCurrent();
} else if (command == back) {
Main.getChooseDeviceForm().removeNewMessageIcon(friend);
Main.getChooseDeviceForm().rearangeElements(null);
if (friendLeft) {
Main.getChooseDeviceForm().removeFriendFromList(friend);
Main.getChooseDeviceForm().removeChatForm(friend);
}
Main.getDisplay().setCurrent(Main.getChooseDeviceForm().getForma());
} else if (command == clear) {
form.deleteAll();
}
}
public boolean isFormShown() {
return form.isShown();
}
public void setFriendLeft() {
friendLeft = true;
}
public boolean getFriendLeft() {
return friendLeft;
}
private Form form;
private Command chat;
private Command back;
private Command clear;
private WriteMessageForm textEnterForm;
private String friend;
private boolean friendLeft;
}
46
Ui.ChooseDevice.java package ui;
import bluetooth.Discovery;
import java.io.IOException;
import java.util.Hashtable;
import java.util.Vector;
import javax.bluetooth.ServiceRecord;
import javax.microedition.lcdui.*;
import main.Main;
public class ChooseDevice
implements CommandListener {
// private static final String noConns = "No one is connected";
private List forma;
static final Command options = new Command("Options", 4, 2);
static final Command refresh = new Command("Refresh", 4, 1);
static final Command about = new Command("About", 4, 3);
static final Command chat = new Command("Chat", 4, 0);
static final Command exit = new Command("Exit", 7, 1);
public static final Ticker tick = new Ticker("Searching for contacts");
private Hashtable chatForm;
private String currentFriendName;
private Vector completeNamesNicknames;
private Image newMessage;
private int command;
public ChooseDevice() {
forma = new List("Online: ", 3);
chatForm = new Hashtable();
completeNamesNicknames = new Vector();
try {
newMessage = Image.createImage("/newmsg.png");
} catch (IOException ioexception) {
ioexception.printStackTrace();
}
forma.setCommandListener(this);
}
public ChatForm getChatForm(String s) {
if (s != null) {
if (chatForm.size() == 0 || !chatForm.containsKey(s)) {
ChatForm chatform = new ChatForm();
chatform.buildBasic();
chatForm.put(s, chatform);
47
return chatform;
} else {
return (ChatForm) chatForm.get(s);
}
} else {
return null;
}
}
public void removeChatForm(String s) {
if (s != null && chatForm.size() != 0 && chatForm.containsKey(s)) {
chatForm.remove(s);
}
}
public void cleanChatForm() {
chatForm.clear();
}
public void newDevice(String s, ServiceRecord servicerecord) {
if (s != null && !completeNamesNicknames.contains(s)) {
if (forma.size() == 0 || forma.size() == 1 && forma.getString(0).equals("No one is
connected")) {
forma.deleteAll();
forma.addCommand(chat);
forma.addCommand(options);
forma.addCommand(refresh);
System.out.println("ADAUGATE!!");
}
completeNamesNicknames.addElement(s);
completeNamesNicknames.addElement(s.substring(0, s.indexOf("_")));
completeNamesNicknames.addElement(servicerecord);
forma.append(s.substring(0, s.indexOf("_")), null);
}
}
public void populateAndSetActive() {
Vector vector = Discovery.getDevices();
byte byte0 = -1;
boolean flag = false;
for (int i = completeNamesNicknames.size() / 3 - 1; i >= 0; i--) {
if (!Main.existsClient((String) completeNamesNicknames.elementAt(i * 3)) &&
!vector.contains((ServiceRecord) completeNamesNicknames.elementAt(i * 3 + 2))) {
completeNamesNicknames.removeElementAt(i * 3 + 2);
completeNamesNicknames.removeElementAt(i * 3 + 1);
completeNamesNicknames.removeElementAt(i * 3);
48
forma.delete(i);
}
}
int j = completeNamesNicknames.size() / 3;
if (forma.size() != 0 && forma.getString(0).equals("No one is connected")) {
forma.deleteAll();
}
for (int k = 0; k < vector.size(); k++) {
String s = (String) vector.elementAt(k);
if (!completeNamesNicknames.contains(s)) {
completeNamesNicknames.addElement(s);
completeNamesNicknames.addElement(s.substring(0, s.indexOf("_")));
completeNamesNicknames.addElement(Discovery.getSelected(k));
forma.append(s.substring(0, s.indexOf("_")), null);
}
}
if (!flag && j != 0) {
flag = true;
}
forma.setCommandListener(this);
rearangeElements(null);
if (vector.size() + j == 0) {
forma.deleteAll();
forma.append("No one is connected", null);
forma.removeCommand(chat);
} else {
forma.addCommand(chat);
}
forma.addCommand(options);
forma.addCommand(refresh);
forma.addCommand(about);
forma.addCommand(exit);
if (forma.isShown()) {
Main.getDisplay().setCurrent(forma);
forma.setCommandListener(this);
}
}
public boolean nameInList(String s) {
if (s.indexOf(" wants to talk with you") != -1) {
s = s.substring(0, s.indexOf(" wants to talk with you"));
boolean flag = false;
for (int i = 0; i < forma.size(); i++) {
if (forma.getString(i).equals(s)) {
49
flag = true;
}
}
return flag;
} else {
return false;
}
}
public void commandAction(Command command1, Displayable displayable) {
if (command1 == exit) {
Main.getDiscover().cancel();
Main.getDiscover().stop();
Main.getServer().stopServer();
} else if (command1 == chat) {
currentFriendName = (String) completeNamesNicknames.elementAt(3 *
forma.getSelectedIndex());
getChatForm(currentFriendName).setFriend(currentFriendName);
getChatForm(currentFriendName).setCurrent(completeNamesNicknames, forma);
} else if (command1 == options) {
Main.getOptionsForm().setActive();
} else if (command1 == refresh) {
Main.getDiscover().cancel();
Main.getDiscover().go();
} else if (command1 == about) {
Main.getAboutForm().setActive();
}
}
public void addToDisplayable(String s) {
if (forma.getString(0).equals("No one is connected")) {
forma.delete(0);
forma.append(s.substring(0, s.indexOf("_")), null);
completeNamesNicknames.addElement(s);
completeNamesNicknames.addElement(s.substring(0, s.indexOf("_")));
completeNamesNicknames.addElement(null);
} else if (!completeNamesNicknames.contains(s)) {
completeNamesNicknames.addElement(s);
completeNamesNicknames.addElement(s.substring(0, s.indexOf("_")));
completeNamesNicknames.addElement(null);
forma.append(s.substring(0, s.indexOf("_")), null);
}
currentFriendName = s;
getChatForm(currentFriendName).setFriend(currentFriendName);
}
50
public ChatForm getChatForm() {
return getChatForm(currentFriendName);
}
public void addChatCommand() {
forma.addCommand(chat);
}
public void addNewMessageIcon(String s) {
int i = completeNamesNicknames.size();
for (int j = 0; j < i; j += 3) {
if (completeNamesNicknames.elementAt(j).equals(s)) {
forma.set(j / 3, s.substring(0, s.indexOf("_")), newMessage);
}
}
}
public void removeNewMessageIcon(String s) {
int i = completeNamesNicknames.size();
for (int j = 0; j < i; j += 3) {
if (completeNamesNicknames.elementAt(j).equals(s)) {
forma.set(j / 3, s.substring(0, s.indexOf("_")), null);
}
}
}
public Displayable getForma() {
return forma;
}
public void removeFriendFromList(String s) {
int i = completeNamesNicknames.indexOf(s);
if (i != -1) {
completeNamesNicknames.removeElementAt(i + 2);
completeNamesNicknames.removeElementAt(i + 1);
completeNamesNicknames.removeElementAt(i);
i /= 3;
forma.delete(i);
Main.removeClient(s);
if (forma.size() == 0) {
forma.append("No one is connected", null);
forma.removeCommand(chat);
}
51
}
}
public void setCommand(int i) {
command = i;
}
public int getCommand() {
return command;
}
public void rearangeElements(Ticker ticker) {
if (forma.size() != 0) {
String as[] = new String[forma.size()];
Image aimage[] = new Image[forma.size()];
for (int i = 0; i < forma.size(); i++) {
as[i] = forma.getString(i);
aimage[i] = forma.getImage(i);
}
forma.deleteAll();
forma.setTicker(ticker);
for (int j = 0; j < as.length; j++) {
forma.append(as[j], aimage[j]);
}
} else {
forma.setTicker(ticker);
}
}
public void initForma() {
forma.addCommand(exit);
formaVisible();
}
public void formaVisible() {
Main.getDisplay().setCurrent(forma);
}
}
Ui.DebugForm.java
package ui;
import javax.microedition.lcdui.*;
import main.Main;
52
public class DebugForm
implements CommandListener {
public DebugForm(String s, String s1, Displayable displayable) {
exit = new Command("Exit", 7, 1);
debugf = new Form(s);
debugf.append(new StringItem(s1, ""));
debugf.addCommand(exit);
parent = displayable;
debugf.setCommandListener(this);
Main.getDisplay().setCurrent(debugf);
}
public void commandAction(Command command, Displayable displayable) {
if (command == exit) {
Main.getDisplay().setCurrent(parent);
}
}
Form debugf;
Command exit;
Displayable parent;
}
Ui.EnterName.java
package ui;
import javax.microedition.lcdui.*;
import javax.microedition.rms.*;
import main.Main;
public class EnterName
implements CommandListener {
private Form enterName;
private Command start;
private Command exit;
private TextField f_nickname_start;
private RecordStore RS;
public static final String REC_STORE = "mobilemessenger_db";
private boolean dataExists;
public EnterName() {
enterName = new Form("Enter your nickname");
start = new Command("Start", 4, 0);
exit = new Command("Exit", 7, 0);
53
f_nickname_start = new TextField("Nickname", "", 15, 0);
RS = null;
dataExists = false;
}
public void populate() {
f_nickname_start.setString("");
enterName.append(f_nickname_start);
enterName.addCommand(start);
enterName.addCommand(exit);
enterName.setCommandListener(this);
}
public void commandAction(Command command, Displayable displayable) {
if (command == start && !f_nickname_start.getString().trim().equals("")) {
Main.getOptionsForm().populate(f_nickname_start.getString());
Main.getOptionsForm().oAcceptSave(f_nickname_start);
Main.getDisplay().setCurrent(Main.getChooseDeviceForm().getForma());
simulateChatPressed();
Main.getServer().setServer(f_nickname_start.getString().trim());
} else if (command == exit) {
Main.getInstance().exitApp();
}
}
public void debug_clearData() {
try {
RecordStore.deleteRecordStore("mobilemessenger_db");
} catch (RecordStoreNotFoundException recordstorenotfoundexception) {
recordstorenotfoundexception.printStackTrace();
} catch (RecordStoreException recordstoreexception) {
recordstoreexception.printStackTrace();
}
}
public void oGetSavedData() {
try {
RS = RecordStore.openRecordStore("mobilemessenger_db", true);
if (RS.getNumRecords() == 4) {
byte abyte0[] = RS.getRecord(1);
OptionsForm.nickname = new String(abyte0, 0, abyte0.length);
abyte0 = RS.getRecord(2);
OptionsForm.alertSound = new String(abyte0, 0, abyte0.length);
abyte0 = RS.getRecord(3);
OptionsForm.vibrate = new String(abyte0, 0, abyte0.length);
abyte0 = RS.getRecord(4);
54
OptionsForm.refreshIndex = Integer.parseInt(new String(abyte0, 0,
abyte0.length));
dataExists = true;
}
RS.closeRecordStore();
} catch (RecordStoreException recordstoreexception) {
System.out.println(recordstoreexception);
recordstoreexception.printStackTrace();
}
}
public void setActive() {
Main.getDisplay().setCurrent(enterName);
}
public void show() {
oGetSavedData();
if (!dataExists) {
populate();
setActive();
} else {
Main.getServer().setServer(OptionsForm.nickname.trim());
Main.getOptionsForm().populate(OptionsForm.nickname);
simulateChatPressed();
}
}
public void simulateChatPressed() {
Main.getChooseDeviceForm().initForma();
if (OptionsForm.refreshIndex == 0) {
Main.getDiscover().go();
} else if (OptionsForm.refreshIndex != 0) {
Main.getOptionsForm().setTimer(true);
}
}
}
Ui.OptionForm.java
package ui;
import bluetooth.Discovery;
import bluetooth.TimerRefresh;
import java.util.Timer;
import javax.microedition.lcdui.*;
import javax.microedition.rms.RecordStore;
55
import javax.microedition.rms.RecordStoreException;
import main.Main;
public class OptionsForm
implements CommandListener {
public OptionsForm() {
options = new Form("Options");
ok = new Command("Ok", 4, 0);
back = new Command("Back", 2, 0);
f_nickname_ok = new TextField("Nickname", "", 15, 0);
dataExists = false;
}
public void populate(String s) {
f_nickname_ok.setString(s);
System.out.println(s);
options.append(f_nickname_ok);
alert = new ChoiceGroup("New Message Alert", 2);
alert.append("Sound Alert", null);
alert.append("Vibrate", null);
if (alertSound.equals("true")) {
alert.setSelectedIndex(0, true);
}
if (vibrate.equals("true")) {
alert.setSelectedIndex(1, true);
}
options.append(alert);
refreshRate = new ChoiceGroup("Refresh Rate", 1);
refreshRate.append("Manual refresh", null);
refreshRate.append("30 s", null);
refreshRate.append("1 min", null);
refreshRate.append("3 min", null);
refreshRate.setSelectedIndex(refreshIndex, true);
options.append(refreshRate);
options.addCommand(ok);
options.addCommand(back);
options.setCommandListener(this);
}
public void setActive() {
Main.getDisplay().setCurrent(options);
}
public void simulateChatPressed() {
if (refreshIndex == 0) {
56
Main.getDiscover().cancel();
Main.getDiscover().go();
}
try {
timerRefresh.cancel();
} catch (Exception exception) {
}
if (refreshIndex != 0) {
timerRefresh = new Timer();
timerRefresh.schedule(new TimerRefresh(false), 100L, refresh[refreshIndex]);
}
Main.getChooseDeviceForm().formaVisible();
}
public void commandAction(Command command, Displayable displayable) {
if (command == ok && !f_nickname_ok.getString().trim().equals("")) {
lastNameOfServer = nickname;
oAcceptSave(f_nickname_ok);
if (!nickname.equals(lastNameOfServer)) {
mustRestart = new Alert("Attention", "You must restart IBM for the new
nickname to be seen by your friends", null, AlertType.CONFIRMATION);
mustRestart.setTimeout(-2);
Main.getDisplay().setCurrent(mustRestart,
Main.getChooseDeviceForm().getForma());
} else {
simulateChatPressed();
}
} else if (command == back) {
Main.getDisplay().setCurrent(Main.getChooseDeviceForm().getForma());
}
}
public void oAcceptSave(TextField textfield) {
try {
RecordStore recordstore = RecordStore.openRecordStore("mobilemessenger_db",
true);
nickname = textfield.getString();
byte abyte0[] = nickname.getBytes();
try {
alertSound = "" + alert.isSelected(0);
} catch (NullPointerException nullpointerexception) {
}
byte abyte1[] = alertSound.getBytes();
try {
vibrate = "" + alert.isSelected(1);
} catch (NullPointerException nullpointerexception1) {
57
}
byte abyte2[] = vibrate.getBytes();
try {
refreshIndex = refreshRate.getSelectedIndex();
} catch (NullPointerException nullpointerexception2) {
}
byte abyte3[] = ("" + refreshIndex).getBytes();
if (recordstore.getNumRecords() == 0) {
recordstore.addRecord(abyte0, 0, abyte0.length);
recordstore.addRecord(abyte1, 0, abyte1.length);
recordstore.addRecord(abyte2, 0, abyte2.length);
recordstore.addRecord(abyte3, 0, abyte3.length);
} else {
recordstore.setRecord(1, abyte0, 0, abyte0.length);
recordstore.setRecord(2, abyte1, 0, abyte1.length);
recordstore.setRecord(3, abyte2, 0, abyte2.length);
recordstore.setRecord(4, abyte3, 0, abyte3.length);
}
recordstore.closeRecordStore();
} catch (RecordStoreException recordstoreexception) {
recordstoreexception.printStackTrace();
}
}
public Timer getTimer() {
return timerRefresh;
}
public void setTimer(boolean flag) {
TimerRefresh timerrefresh = new TimerRefresh(flag);
timerRefresh = new Timer();
timerRefresh.schedule(timerrefresh, 100L, refresh[refreshIndex]);
}
private Form options;
private Command ok;
private Command back;
private TextField f_nickname_ok;
private ChoiceGroup alert;
private ChoiceGroup refreshRate;
private String lastNameOfServer;
public static String nickname = "";
public static String alertSound = "false";
public static String vibrate = "false";
public static int refreshIndex = 0;
private int refresh[] = {
0, 30000, 60000, 0x2bf20
58
};
private boolean dataExists;
private Timer timerRefresh;
private Alert mustRestart;
}
Ui.WriteMessageForm.java
package ui;
import bluetooth.Client;
import bluetooth.Server;
import java.io.PrintStream;
import javax.microedition.lcdui.*;
import main.Main;
public class WriteMessageForm implements CommandListener {
public WriteMessageForm(ChatForm chatform) {
textToSend = new TextBox("Type message", "", 120, 0);
textToSend.addCommand(back);
textToSend.addCommand(send);
textToSend.setCommandListener(this);
parent = chatform;
}
public void commandAction(Command command, Displayable displayable) {
System.out.println("text to send_" + textToSend);
if (command == send && textToSend.getString() != null &&
!textToSend.getString().trim().equals("")) {
try {
Main.getClient(null, friend, false).talk(textToSend.getString());
parent.addMsg(Server.serverName.substring(0,
Server.serverName.indexOf("_")) + ": " + textToSend.getString(), Server.serverName);
parent.setCurrent(null, null);
} catch (NullPointerException nullpointerexception) {
nullpointerexception.printStackTrace();
}
} else if (command == back) {
parent.setCurrent(null, null);
}
}
public void setCurrent() {
Main.getDisplay().setCurrent(textToSend);
textToSend.setString("");
textToSend.setTicker(null);
59
}
public void setFriend(String s) {
friend = s;
}
private TextBox textToSend;
private static final Command send = new Command("Send", 4, 0);
private static final Command back = new Command("Back", 2, 0);
private ChatForm parent;
private String friend;
}
60
6 Conclusion
The application was tested using sun java wireless toolkit, an emulator.
Alternatively
It can be tested with Impronto Simulator for Bluetooth Technologies.
7 Future Work
Future use IBM application and possible development can take following
directions.
1) First, create a much more comprehensive chat system containing
rooms, user groups, multimedia data, encryption of messages, etc.
2) A way to aid Visually Impaired navigates in buildings. Some of these
possible directions can be implemented in the context of our thesis.
61
8 List of Literature
� J2ME:The Complete Reference by James Keogh
� Bluetooth Application Programming with JAVA APIs by Bala Kumar, Paul
J.Kline & Timothy J.Thompson
� http://developers.sun.com/mobility/midp/articles/bluetooth1/
� Mobile Information Device Profile for Java™ 2 Micro Edition by JCP
� http://java.sun.com/products/midp/
� http://www.jsr82.com/jsr-82-sample-spp-server-and-client/
� http://www.jsr82.com/simulating-jabwt-applications-using-jsr-82-simulators/