Serial over Bluetooth simple test client.

Quickly share your Android Code Snippets here...

Serial over Bluetooth simple test client.

Postby XCaffeinated » Fri Feb 12, 2010 2:48 am

In answer to a request in Google Groups for more info regarding Bluetooth using SPP in Android , I submitted a rather lengthy post there.

The code in that post came out an unreadable mess, and as I can't go back and edit it, I'm going to use anddev's great forum/BBCode tools to repost the code here.

It's longer than a snippet, but not a tutorial; I hope people get use out of it.

Quick summary: this is a lightweight non-threaded Bluetooth Android client (2.0 or higher) that will connect to a listener (server) and send a simple message, using the well-known SPP (Serial Port Profile) service and UUID. It is intended for quick testing and to show how a basic client-side connection is established in Android. The Bluetooth Chat Sample in the SDK is a fantastic reference, once you understand the basics, and should probably be used for anything more complicated than simple testing.

Additional notes about the code are contained in my post linked above, and if anyone would like the Eclipse project, just PM me.

Hope you find it useful!
-XCaf

Syntax: [ Download ] [ Hide ]
Using java Syntax Highlighting
  1. package com.example.thinbtclient;
  2.  
  3. import java.io.IOException;
  4. import java.io.OutputStream;
  5. import java.util.UUID;
  6.  
  7. import android.app.Activity;
  8. import android.bluetooth.BluetoothAdapter;
  9. import android.bluetooth.BluetoothDevice;
  10. import android.bluetooth.BluetoothSocket;
  11. import android.os.Bundle;
  12. import android.util.Log;
  13. import android.widget.Toast;
  14.  
  15. public class ThinBTClient extends Activity {
  16.        
  17.         private static final String TAG = "THINBTCLIENT";
  18.         private static final boolean D = true;
  19.         private BluetoothAdapter mBluetoothAdapter = null;
  20.         private BluetoothSocket btSocket = null;
  21.         private OutputStream outStream = null;
  22.         // Well known SPP UUID (will *probably* map to
  23.         // RFCOMM channel 1 (default) if not in use);
  24.         // see comments in onResume().
  25.         private static final UUID MY_UUID =
  26.                         UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
  27.  
  28.         // ==> hardcode your server's MAC address here <==
  29.         private static String address = "XX:XX:XX:XX:XX:XX";
  30.  
  31.         /** Called when the activity is first created. */
  32.         @Override
  33.         public void onCreate(Bundle savedInstanceState) {
  34.                 super.onCreate(savedInstanceState);
  35.                 setContentView(R.layout.main);
  36.  
  37.                 if (D)
  38.                         Log.e(TAG, "+++ ON CREATE +++");
  39.  
  40.                 mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
  41.                 if (mBluetoothAdapter == null) {
  42.                         Toast.makeText(this,
  43.                                 "Bluetooth is not available.",
  44.                                 Toast.LENGTH_LONG).show();
  45.                         finish();
  46.                         return;
  47.                 }
  48.  
  49.                 if (!mBluetoothAdapter.isEnabled()) {
  50.                         Toast.makeText(this,
  51.                                 "Please enable your BT and re-run this program.",
  52.                                 Toast.LENGTH_LONG).show();
  53.                         finish();
  54.                         return;
  55.                 }
  56.  
  57.                 if (D)
  58.                         Log.e(TAG, "+++ DONE IN ON CREATE, GOT LOCAL BT ADAPTER +++");
  59.         }
  60.  
  61.         @Override
  62.         public void onStart() {
  63.                 super.onStart();
  64.                 if (D)
  65.                         Log.e(TAG, "++ ON START ++");
  66.         }
  67.  
  68.         @Override
  69.         public void onResume() {
  70.                 super.onResume();
  71.  
  72.                 if (D) {
  73.                         Log.e(TAG, "+ ON RESUME +");
  74.                         Log.e(TAG, "+ ABOUT TO ATTEMPT CLIENT CONNECT +");
  75.                 }
  76.  
  77.                 // When this returns, it will 'know' about the server,
  78.                 // via it's MAC address.
  79.                 BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
  80.  
  81.                 // We need two things before we can successfully connect
  82.                 // (authentication issues aside): a MAC address, which we
  83.                 // already have, and an RFCOMM channel.
  84.                 // Because RFCOMM channels (aka ports) are limited in
  85.                 // number, Android doesn't allow you to use them directly;
  86.                 // instead you request a RFCOMM mapping based on a service
  87.                 // ID. In our case, we will use the well-known SPP Service
  88.                 // ID. This ID is in UUID (GUID to you Microsofties)
  89.                 // format. Given the UUID, Android will handle the
  90.                 // mapping for you. Generally, this will return RFCOMM 1,
  91.                 // but not always; it depends what other BlueTooth services
  92.                 // are in use on your Android device.
  93.                 try {
  94.                         btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
  95.                 } catch (IOException e) {
  96.                         Log.e(TAG, "ON RESUME: Socket creation failed.", e);
  97.                 }
  98.  
  99.                 // Discovery may be going on, e.g., if you're running a
  100.                 // 'scan for devices' search from your handset's Bluetooth
  101.                 // settings, so we call cancelDiscovery(). It doesn't hurt
  102.                 // to call it, but it might hurt not to... discovery is a
  103.                 // heavyweight process; you don't want it in progress when
  104.                 // a connection attempt is made.
  105.                 mBluetoothAdapter.cancelDiscovery();
  106.  
  107.                 // Blocking connect, for a simple client nothing else can
  108.                 // happen until a successful connection is made, so we
  109.                 // don't care if it blocks.
  110.                 try {
  111.                         btSocket.connect();
  112.                         Log.e(TAG, "ON RESUME: BT connection established, data transfer link open.");
  113.                 } catch (IOException e) {
  114.                         try {
  115.                                 btSocket.close();
  116.                         } catch (IOException e2) {
  117.                                 Log.e(TAG,
  118.                                         "ON RESUME: Unable to close socket during connection failure", e2);
  119.                         }
  120.                 }
  121.  
  122.                 // Create a data stream so we can talk to server.
  123.                 if (D)
  124.                         Log.e(TAG, "+ ABOUT TO SAY SOMETHING TO SERVER +");
  125.  
  126.                 try {
  127.                         outStream = btSocket.getOutputStream();
  128.                 } catch (IOException e) {
  129.                         Log.e(TAG, "ON RESUME: Output stream creation failed.", e);
  130.                 }
  131.  
  132.                 String message = "Hello message from client to server.";
  133.                 byte[] msgBuffer = message.getBytes();
  134.                 try {
  135.                         outStream.write(msgBuffer);
  136.                 } catch (IOException e) {
  137.                         Log.e(TAG, "ON RESUME: Exception during write.", e);
  138.                 }
  139.         }
  140.  
  141.         @Override
  142.         public void onPause() {
  143.                 super.onPause();
  144.  
  145.                 if (D)
  146.                         Log.e(TAG, "- ON PAUSE -");
  147.  
  148.                 if (outStream != null) {
  149.                         try {
  150.                                 outStream.flush();
  151.                         } catch (IOException e) {
  152.                                 Log.e(TAG, "ON PAUSE: Couldn't flush output stream.", e);
  153.                         }
  154.                 }
  155.  
  156.                 try     {
  157.                         btSocket.close();
  158.                 } catch (IOException e2) {
  159.                         Log.e(TAG, "ON PAUSE: Unable to close socket.", e2);
  160.                 }
  161.         }
  162.  
  163.         @Override
  164.         public void onStop() {
  165.                 super.onStop();
  166.                 if (D)
  167.                         Log.e(TAG, "-- ON STOP --");
  168.         }
  169.  
  170.         @Override
  171.         public void onDestroy() {
  172.                 super.onDestroy();
  173.                 if (D)
  174.                         Log.e(TAG, "--- ON DESTROY ---");
  175.         }
  176. }
Parsed in 0.048 seconds, using GeSHi 1.0.8.4


and you will need to put the following in your project's manifest:
Syntax: [ Download ] [ Hide ]
Using xml Syntax Highlighting
  1. <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
  2. <uses-permission android:name="android.permission.BLUETOOTH" />  
Parsed in 0.001 seconds, using GeSHi 1.0.8.4
XCaffeinated
Developer
Developer
 
Posts: 25
Joined: Sun Nov 29, 2009 10:16 pm

Top

Bluetooth project

Postby netgeek » Mon May 10, 2010 4:22 am

Hi

I am working on an android Bluetooth project. But I seem to face problems with the server code....
It would be really helpful if u can post the eclipse project...thanks a ton
Net Geek
netgeek
Once Poster
Once Poster
 
Posts: 1
Joined: Mon May 10, 2010 4:09 am

Postby davmont » Tue May 11, 2010 10:14 am

thanks for sharing your code!

im working in an app that uses BT serial access to a sensor (in addition to SOAP, WiFi...), this is going to make things easier...

thanks a lot ^_^
davmont
Junior Developer
Junior Developer
 
Posts: 18
Joined: Wed May 05, 2010 10:00 am
Location: Europe

Re: Serial over Bluetooth simple test client.

Postby poeschlorn » Tue Jun 15, 2010 1:16 pm

Hi, thanks for this nice little tutorial.
I assume that receiving data works analogue, only using inputstream instead of outputstream? is this right?

Another question is, how to get the MAC address of the server automatically?


Greets from northern europe,
poeschlorn
poeschlorn
Freshman
Freshman
 
Posts: 4
Joined: Thu May 27, 2010 7:19 am

Re: Serial over Bluetooth simple test client.

Postby peru0002 » Tue Jul 20, 2010 3:47 am

Hi,

I have tried the code snippet. My server will be another Android phone also running on 2.1 but I could not receive any string. Must I also write an app for the server to receive the string?

I have also tried to pair up the phones and tried too but no difference.

Any idea what is causing the problem?

Thanks In Advance,
Perumal
peru0002
Developer
Developer
 
Posts: 45
Joined: Thu Jan 21, 2010 5:56 am

Re: Serial over Bluetooth simple test client.

Postby Wiseman20 » Fri Jul 30, 2010 1:51 am

I am having a lot of problems with my bluetooth after running this program. Whenever I activate BlueTooth or disable it I am asked to force close com.android.settings. Whenever I try going to Settings->Wireless & Network it asks me to force quit com.android.settings as well. I have an Evo with 2.1, anyone have an idea how to fix it. Ive uninstalled the program and restarted the phone. Ance restarted I can get into Wireless & Network but once I enable BlueTooth it crashes and wont let me back in the screen
Wiseman20
Junior Developer
Junior Developer
 
Posts: 14
Joined: Mon Jul 26, 2010 9:57 pm

Top

Re: Serial over Bluetooth simple test client.

Postby dodojpjp » Mon Aug 23, 2010 6:21 pm

thanks a lots
dodojpjp
Once Poster
Once Poster
 
Posts: 1
Joined: Mon Aug 23, 2010 6:17 pm

Re: Serial over Bluetooth simple test client.

Postby dbeach » Fri Feb 04, 2011 11:21 pm

dodojpjp wrote:thanks a lots


+1 - The UUID was the piece I was missing to enable my proof of concept! Now, back to coding... :D :D :D
dbeach
Once Poster
Once Poster
 
Posts: 1
Joined: Fri Feb 04, 2011 11:17 pm

Re: Serial over Bluetooth simple test client.

Postby sasilg » Tue Jun 28, 2011 12:27 pm

Hi,

I am working on Android Bluetooth spp application.

Through spp i want to connect to BT device.But in my case i am able to establish connection to BT device what i have.
sasilg
Once Poster
Once Poster
 
Posts: 1
Joined: Tue Jun 28, 2011 12:21 pm

Re: Serial over Bluetooth simple test client.

Postby prokopis » Fri Dec 02, 2011 10:31 pm

hi
am trying to do something similar and i have some quaestions if you want to help me.
as i read in you article in http://groups.google.com/group/android- ... fe50135738? it says that you will need a pin in order to android to let you connect and send on receive the data. in which step it ask you the pin?
my application in connect with allready paired device(need a pin in order to be paired not the 1234, device pin)
it connect but i never can send or receive the data back to me. it might be what you are saying the pin 1234/12345 or it might be something else?
thanks
prokopis
Once Poster
Once Poster
 
Posts: 1
Joined: Fri Dec 02, 2011 10:27 pm

Re: Serial over Bluetooth simple test client.

Postby milind-kanani » Tue Jan 17, 2012 9:55 am

hi i am trying your code but get following error.
java.lang.IllegalArgumentException: XX:XX:XX:XX:XX:XX is not a valid Bluetooth address

please help me out and if posible send me eclipse project by PM
milind-kanani
Once Poster
Once Poster
 
Posts: 1
Joined: Tue Jan 04, 2011 10:13 am

Re: Serial over Bluetooth simple test client.

Postby tdjohnson » Tue Feb 07, 2012 10:20 am

hi i also am trying your code and unfortunately I get following error.
java.lang.IllegalArgumentException: XX:XX:XX:XX:XX:XX is not a valid Bluetooth address
tdjohnson
Once Poster
Once Poster
 
Posts: 1
Joined: Tue Feb 07, 2012 10:12 am

Re: Serial over Bluetooth simple test client.

Postby singamasae » Tue Feb 28, 2012 6:55 am

hi,
is it possible to use this application with bluetooth mobile printer? or need some tweaks?
i try this sample code. the appliaction correctly connected to printer but nothing printing...
singamasae
Freshman
Freshman
 
Posts: 2
Joined: Tue Feb 28, 2012 6:23 am

Re: Serial over Bluetooth simple test client.

Postby AndroidStarter » Wed Mar 07, 2012 10:07 am

singamasae wrote:hi,
is it possible to use this application with bluetooth mobile printer? or need some tweaks?
i try this sample code. the appliaction correctly connected to printer but nothing printing...


what printer do you use? do you succeded to print out anything since your comment using this tutorial? can you provide some source code if you succeded?

thanks advanced.
AndroidStarter
Freshman
Freshman
 
Posts: 2
Joined: Tue Dec 27, 2011 2:09 pm

Re: Serial over Bluetooth simple test client.

Postby singamasae » Thu Mar 08, 2012 6:25 am

@AndroidStarter:
i use evolute impress mobile printer
but still fail to print when i use the source above :(
singamasae
Freshman
Freshman
 
Posts: 2
Joined: Tue Feb 28, 2012 6:23 am

Top
Next

Return to Code Snippets for Android

Who is online

Users browsing this forum: No registered users and 4 guests