A sample code for Bluetooth chat is given in androidsdk sample, and this article is only slightly modified into a simple server and client-mode application to accommodate one-to-one data transfer in game development.
Because the Bluetooth settings in the game occur in a new thread, the Bluetooth status and read information is transmitted to the display activity in a handler manner.
1 Bluetooth enabled, including the configuration in XML:
<uses-permission android:name= "Android.permission.BLUETOOTH_ADMIN"/>
<uses-permission android:name= "Android.permission.BLUETOOTH"/>
Get Bluetooth adapter
bluetoothadapter btadapter = Bluetoothservice.getinstance (). Getbtadapter ();
Turn on Bluetooth
if (!btadapter.isenabled ()) {
Intent enableintent = new Intent (bluetoothadapter.action_request_enable );
Startactivityforresult (Enableintent, Constantsutil.enable_bluetooth);
}
2 in the current activity to obtain Bluetooth open results, and according to the specific situation of Bluetooth processing
@Override protected void Onactivityresult (int requestcode, int resultcode, Intent data) {switch (Requestcode) { Case ConstantsUtil.ENABLE_BLUETOOTH:if (ResultCode = = ACTIVITY.RESULT_OK) {BLUETOOTHP
Rocess (Psystem.isserver);
else {finish (); }} public void Bluetoothprocess (Boolean isserver) {bluetoothservice.getinstance (). Setshandler (Mhandler)
; if (isserver) {//If it is a Bluetooth server, you need to turn on the discovery service and start the Bluetooth server if (Btadapter.getscanmode ()!= Bluetoothadapter.scan_mode_connectable_
DISCOVERABLE) {Intent discoverableintent = new Intent (bluetoothadapter.action_request_discoverable);
Discoverableintent.putextra (bluetoothadapter.extra_discoverable_duration, 180);
StartActivity (discoverableintent);
Bluetoothservice.getinstance (). Start ();
else {//If the Bluetooth client scans around the available Bluetooth device bluetoothnames = new arraylist<string> ();
Bluttoothdevices = new arraylist<bluetoothdevice> (); Add a filter and register the broadcast to monitor Bluetooth discovery information Intentfilter filter = new Intentfilter (bluetoothdevice.action_found);
This.registerreceiver (mreceiver, filter);
Filter = new Intentfilter (bluetoothadapter.action_discovery_finished);
This.registerreceiver (mreceiver, filter);
Start scanning dodiscovery ();
} public void Dodiscovery () {if (btadapter.isdiscovering ()) {btadapter.canceldiscovery ());
} btadapter.startdiscovery ();
}
3 Bluetooth Broadcast Receiver
Private final Broadcastreceiver mreceiver = new Broadcastreceiver () {
@Override public
void OnReceive (context Context, Intent Intent) {
String action = intent.getaction ();
if (BluetoothDevice.ACTION_FOUND.equals (ACTION)) {
Bluetoothdevice device = Intent
. Getparcelableextra ( Bluetoothdevice.extra_device);
if (device.getname ()!= null &&!device.getname (). Trim (). Equals (")" {
Bluetoothnames.add (device.getname ());
Bluttoothdevices.add (device);
}
else if (bluetoothadapter.action_discovery_finished
. Equals (ACTION)) {
btadapter.canceldiscovery ();
TestActivity.this.unregisterReceiver (this);
}
}
;
4 above is Bluetooth basic configuration and discovery. Now for Bluetooth listening and connecting:
Bluetooth Server Listener Code:
public void Start () {
bluetoothserversocket serversocket = null;
try {
serversocket = Btadapter.listenusingrfcommwithservicerecord ("Jumpformeapp", my_uuid_secure);
Changestate (Constantsutil.bt_state_listen);
Btsocket = Serversocket.accept ();
} catch (IOException e) {
} finally {
try {
serversocket.close ();
} catch (IOException e) {
}
}< C12/>if (btsocket!= null) {
changestate (constantsutil.bt_state_connected);
}
}
Client Connection code:
public void Connect (Bluetoothdevice device) {
try {
btadapter.canceldiscovery ();
Btsocket = Device.createrfcommsockettoservicerecord (my_uuid_secure);
Changestate (constantsutil.bt_state_connecting);
Btsocket.connect ();
} catch (IOException e) {
}
changestate (constantsutil.bt_state_connected);
}
5 using Bluetooth for message delivery, create new threads to handle read and write operations (see Bluetoothchat Sample Connectedthread):
Class Connectedthread extends Thread {private final bluetoothsocket mmsocket;
Private final InputStream Mminstream;
Private final OutputStream Mmoutstream;
Public Connectedthread (Bluetoothsocket socket) {mmsocket = socket;
InputStream tmpin = null;
OutputStream tmpout = null;
try {tmpin = Socket.getinputstream ();
Tmpout = Socket.getoutputstream ();
catch (IOException e) {log.e (TAG, "temp sockets not created", e);
} Mminstream = Tmpin;
Mmoutstream = Tmpout;
public void Run () {byte[] buffer = new byte[1024];
int bytes;
while (true) {try {bytes = mminstream.read (buffer); if (Transhandler!= null) {//Notification data transfer Processor Transhandler.sendmessage (Transhandler.obtainmessage (constantsutil.bt_re
AD, Bytes,-1, buffer);
The catch (IOException e) {log.e (TAG, "Disconnected", e);
Break
}} public void write (byte[) buffer {try {mmoutstream.write (buffer); catch (IoexcEption e) {log.e (TAG, "Exception during write", e);
} public void Cancel () {try {mmsocket.close ();
catch (IOException e) {log.e (TAG, "close () of Connect socket failed", e); }
}
}