Java bluetooth передача данных

Send text through Bluetooth from Java Server to Android Client

First of all. don’t redirect me to Bluetooth Chat and I have fully read it. I have an Android Client which stablishes the connection properly with the server, and what’s most I can send text to the server in my pc and show it correctly, but I can’t do the opposite action, send a simple string from the server to the client and show it in my android app. I don’t want to implement a chat is just to show how BT communication works between a Java Server and Android Client. To make it easy: I send the text at the end of the startServer() method in the server class. I try to read the text from the server at the beginning of onPause(). **

[Solved] Solution Below

/*. libraries here. */ public class ConnectTest extends Activity < TextView out; private static final int REQUEST_ENABLE_BT = 1; private BluetoothAdapter btAdapter = null; private BluetoothSocket btSocket = null; private OutputStream outStream = null; // Well known SPP UUID private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); // Insert your server's MAC address private static String address = "00:10:60:AA:B9:B2"; /** Called when the activity is first created. */ public void onCreate(Bundle savedInstanceState) < super.onCreate(savedInstanceState); setContentView(R.layout.main); out = (TextView) findViewById(R.id.out); out.append("\n. In onCreate(). "); btAdapter = BluetoothAdapter.getDefaultAdapter(); CheckBTState(); >public void onStart() < super.onStart(); out.append("\n. In onStart(). "); >public void onResume() < super.onResume(); out.append("\n. In onResume. \n. Attempting client connect. "); // Set up a pointer to the remote node using it's address. BluetoothDevice device = btAdapter.getRemoteDevice(address); // Two things are needed to make a connection: // A MAC address, which we got above. // A Service ID or UUID. In this case we are using the // UUID for SPP. try < btSocket = device.createRfcommSocketToServiceRecord(MY_UUID); >catch (IOException e) < AlertBox("Fatal Error", "In onResume() and socket create failed: " + e.getMessage() + "."); >// Discovery is resource intensive. Make sure it isn't going on // when you attempt to connect and pass your message. btAdapter.cancelDiscovery(); // Establish the connection. This will block until it connects. try < btSocket.connect(); out.append("\n. Connection established and data link opened. "); >catch (IOException e) < try < btSocket.close(); >catch (IOException e2) < AlertBox("Fatal Error", "In onResume() and unable to close socket during connection failure" + e2.getMessage() + "."); >> // Create a data stream so we can talk to server. out.append("\n. Sending message to server. "); String message = "Hello from Android.\n"; out.append("\n\n. The message that we will send to the server is: "+message); try < outStream = btSocket.getOutputStream(); >catch (IOException e) < AlertBox("Fatal Error", "In onResume() and output stream creation failed:" + e.getMessage() + "."); >byte[] msgBuffer = message.getBytes(); try < outStream.write(msgBuffer); >catch (IOException e) < String msg = "In onResume() and an exception occurred during write: " + e.getMessage(); if (address.equals("00:00:00:00:00:00")) msg = msg + ".\n\nUpdate your server address from 00:00:00:00:00:00 to the correct address on line 37 in the java code"; msg = msg + ".\n\nCheck that the SPP UUID: " + MY_UUID.toString() + " exists on server.\n\n"; AlertBox("Fatal Error", msg); >> public void onPause() < super.onPause(); //out.append("\n. Hello\n"); InputStream inStream; try < inStream = btSocket.getInputStream(); BufferedReader bReader=new BufferedReader(new InputStreamReader(inStream)); String lineRead=bReader.readLine(); out.append("\n. "+lineRead+"\n"); >catch (IOException e) < // TODO Auto-generated catch block e.printStackTrace(); >out.append("\n. In onPause(). "); if (outStream != null) < try < outStream.flush(); >catch (IOException e) < AlertBox("Fatal Error", "In onPause() and failed to flush output stream: " + e.getMessage() + "."); >> try < btSocket.close(); >catch (IOException e2) < AlertBox("Fatal Error", "In onPause() and failed to close socket." + e2.getMessage() + "."); >> public void onStop() < super.onStop(); out.append("\n. In onStop(). "); >public void onDestroy() < super.onDestroy(); out.append("\n. In onDestroy(). "); >private void CheckBTState() < // Check for Bluetooth support and then check to make sure it is turned on // Emulator doesn't support Bluetooth and will return null if(btAdapter==null) < AlertBox("Fatal Error", "Bluetooth Not supported. Aborting."); >else < if (btAdapter.isEnabled()) < out.append("\n. Bluetooth is enabled. "); >else < //Prompt user to turn on Bluetooth Intent enableBtIntent = new Intent(btAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT); >> > public void AlertBox( String title, String message ) < new AlertDialog.Builder(this) .setTitle( title ) .setMessage( message + " Press OK to exit." ) .setPositiveButton("OK", new OnClickListener() < public void onClick(DialogInterface arg0, int arg1) < finish(); >>).show(); > > 
 import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import javax.bluetooth.*; import javax.microedition.io.*; /** * Class that implements an SPP Server which accepts single line of * message from an SPP client and sends a single line of response to the client. */ public class SimpleSPPServer < //start server private void startServer() throws IOException< //Create a UUID for SPP UUID uuid = new UUID("1101", true); //Create the servicve url String connectionString = "btspp://localhost:" + uuid +";name=Sample SPP Server"; //open server url StreamConnectionNotifier streamConnNotifier = (StreamConnectionNotifier)Connector.open( connectionString ); //Wait for client connection System.out.println("\nServer Started. Waiting for clients to connect. "); StreamConnection connection=streamConnNotifier.acceptAndOpen(); RemoteDevice dev = RemoteDevice.getRemoteDevice(connection); System.out.println("Remote device address: "+dev.getBluetoothAddress()); System.out.println("Remote device name: "+dev.getFriendlyName(true)); //read string from spp client InputStream inStream=connection.openInputStream(); BufferedReader bReader=new BufferedReader(new InputStreamReader(inStream)); String lineRead=bReader.readLine(); System.out.println(lineRead); //send response to spp client OutputStream outStream=connection.openOutputStream(); BufferedWriter bWriter=new BufferedWriter(new OutputStreamWriter(outStream)); bWriter.write("Response String from SPP Server\r\n"); /*PrintWriter pWriter=new PrintWriter(new OutputStreamWriter(outStream)); pWriter.write("Response String from SPP Server\r\n"); pWriter.flush(); pWriter.close();*/ streamConnNotifier.close(); >public static void main(String[] args) throws IOException < //display local device address and name LocalDevice localDevice = LocalDevice.getLocalDevice(); System.out.println("Address: "+localDevice.getBluetoothAddress()); System.out.println("Name: "+localDevice.getFriendlyName()); SimpleSPPServer sampleSPPServer=new SimpleSPPServer(); sampleSPPServer.startServer(); >> 

Solution: It’s just a small change in the server side. I don’t know why but instead of using BufferedWrite to write in the socket, we need to use PrinterWriter to do so. I add that piece of code modified: BT Server:

 . //read string from spp client InputStream inStream=connection.openInputStream(); BufferedReader bReader=new BufferedReader(new InputStreamReader(inStream)); String lineRead=bReader.readLine(); System.out.println(lineRead); //send response to spp client OutputStream outStream=connection.openOutputStream(); PrintWriter pWriter=new PrintWriter(new OutputStreamWriter(outStream)); pWriter.write("Response String from SPP Server\r\n"); pWriter.flush(); pWriter.close(); streamConnNotifier.close(); . 

Источник

Читайте также:  Iphone se 2016 версия блютуз

How to send/receive messages via bluetooth android studio

I am trying to create an app that allows a string to be sent from one Android phone to another. The code for this is provided below. However, it isn’t working as I keep getting exceptions from the try catch piece of code under the pairDevice() section. Does anyone know why I might be getting this?

import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothSocket; import android.content.Intent; import android.os.ParcelUuid; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Scanner; import java.util.Set; public class MainActivity extends AppCompatActivity < InputStream inStream; OutputStream outputStream; private static final int REQUEST_ENABLE_BT = 1; public void pairDevice() < BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if (bluetoothAdapter != null && !bluetoothAdapter.isEnabled()) < Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);>Set pairedDevices = bluetoothAdapter.getBondedDevices(); if (pairedDevices.size() > 0) < Object[] devices = pairedDevices.toArray(); BluetoothDevice device = (BluetoothDevice) devices[0]; ParcelUuid[] uuid = device.getUuids(); try < BluetoothSocket socket = device.createInsecureRfcommSocketToServiceRecord(uuid[0].getUuid()); socket.connect(); Toast.makeText(this, "Socket connected", Toast.LENGTH_LONG).show(); outputStream = socket.getOutputStream(); inStream = socket.getInputStream(); >catch (IOException e) < Toast.makeText(this, "Exception found", Toast.LENGTH_LONG).show(); >> > public void SendMessage(View v) < EditText outMessage = (EditText) findViewById(R.id.editText); try < if (outputStream != null) outputStream.write(outMessage.toString().getBytes()); TextView displayMessage = (TextView) findViewById(R.id.textView); Scanner s = new Scanner(inStream).useDelimiter("\\A"); displayMessage.setText(s.hasNext() ? s.next() : ""); >catch (IOException e) Toast.makeText(this,"No output stream", Toast.LENGTH_LONG).show(); > @Override protected void onCreate(Bundle savedInstanceState)

3 Answers 3

I have made few changes to your app:-

Firstly, I shifted the code responsible for creating the Bluetooth connection to ConnectThread .

2) Added AcceptThread responsible for listening incoming connections and ConnectedThread maintaining the BTConnection, Sending the data, and receiving incoming data through input/output streams respectively. 3) Created 2 buttons to start ConnectThread and AcceptThread.

NOTE: Make sure both the devices are paired and the device that you are trying to connect to is at the top of the list(or just remove all the paired devices from both the devices and only pair the devices that you want to connect). Also, you must start the AcceptThread before ConnectThread

MAINACTIVITY.JAVA

public class MainActivity extends AppCompatActivity < private static final UUID MY_UUID_INSECURE = UUID.fromString("8ce255c0-200a-11e0-ac64-0800200c9a66"); private static final int REQUEST_ENABLE_BT = 1; BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); private BluetoothDevice mmDevice; private UUID deviceUUID; ConnectedThread mConnectedThread; private Handler handler; String TAG = "MainActivity"; EditText send_data; TextView view_data; StringBuilder messages; public void pairDevice(View v) < SetpairedDevices = bluetoothAdapter.getBondedDevices(); Log.e("MAinActivity", "" + pairedDevices.size() ); if (pairedDevices.size() > 0) < Object[] devices = pairedDevices.toArray(); BluetoothDevice device = (BluetoothDevice) devices[0]; //ParcelUuid[] uuid = device.getUuids(); Log.e("MAinActivity", "" + device ); //Log.e("MAinActivity", "" + uuid) ConnectThread connect = new ConnectThread(device,MY_UUID_INSECURE); connect.start(); >> private class ConnectThread extends Thread < private BluetoothSocket mmSocket; public ConnectThread(BluetoothDevice device, UUID uuid) < Log.d(TAG, "ConnectThread: started."); mmDevice = device; deviceUUID = uuid; >public void run() < BluetoothSocket tmp = null; Log.i(TAG, "RUN mConnectThread "); // Get a BluetoothSocket for a connection with the // given BluetoothDevice try < Log.d(TAG, "ConnectThread: Trying to create InsecureRfcommSocket using UUID: " +MY_UUID_INSECURE ); tmp = mmDevice.createRfcommSocketToServiceRecord(MY_UUID_INSECURE); >catch (IOException e) < Log.e(TAG, "ConnectThread: Could not create InsecureRfcommSocket " + e.getMessage()); >mmSocket = tmp; // Make a connection to the BluetoothSocket try < // This is a blocking call and will only return on a // successful connection or an exception mmSocket.connect(); >catch (IOException e) < // Close the socket try < mmSocket.close(); Log.d(TAG, "run: Closed Socket."); >catch (IOException e1) < Log.e(TAG, "mConnectThread: run: Unable to close connection in socket " + e1.getMessage()); >Log.d(TAG, "run: ConnectThread: Could not connect to UUID: " + MY_UUID_INSECURE ); > //will talk about this in the 3rd video connected(mmSocket); > public void cancel() < try < Log.d(TAG, "cancel: Closing Client Socket."); mmSocket.close(); >catch (IOException e) < Log.e(TAG, "cancel: close() of mmSocket in Connectthread failed. " + e.getMessage()); >> > private void connected(BluetoothSocket mmSocket) < Log.d(TAG, "connected: Starting."); // Start the thread to manage the connection and perform transmissions mConnectedThread = new ConnectedThread(mmSocket); mConnectedThread.start(); >private class ConnectedThread extends Thread < private final BluetoothSocket mmSocket; private final InputStream mmInStream; private final OutputStream mmOutStream; public ConnectedThread(BluetoothSocket socket) < Log.d(TAG, "ConnectedThread: Starting."); mmSocket = socket; InputStream tmpIn = null; OutputStream tmpOut = null; try < tmpIn = mmSocket.getInputStream(); tmpOut = mmSocket.getOutputStream(); >catch (IOException e) < e.printStackTrace(); >mmInStream = tmpIn; mmOutStream = tmpOut; > public void run() < byte[] buffer = new byte[1024]; // buffer store for the stream int bytes; // bytes returned from read() // Keep listening to the InputStream until an exception occurs while (true) < // Read from the InputStream try < bytes = mmInStream.read(buffer); final String incomingMessage = new String(buffer, 0, bytes); Log.d(TAG, "InputStream: " + incomingMessage); runOnUiThread(new Runnable() < @Override public void run() < view_data.setText(incomingMessage); >>); > catch (IOException e) < Log.e(TAG, "write: Error reading Input Stream. " + e.getMessage() ); break; >> > public void write(byte[] bytes) < String text = new String(bytes, Charset.defaultCharset()); Log.d(TAG, "write: Writing to outputstream: " + text); try < mmOutStream.write(bytes); >catch (IOException e) < Log.e(TAG, "write: Error writing to output stream. " + e.getMessage() ); >> /* Call this from the main activity to shutdown the connection */ public void cancel() < try < mmSocket.close(); >catch (IOException e) < >> > public void SendMessage(View v) < byte[] bytes = send_data.getText().toString().getBytes(Charset.defaultCharset()); mConnectedThread.write(bytes); >@Override protected void onCreate(Bundle savedInstanceState) < super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); send_data =(EditText) findViewById(R.id.editText); view_data = (TextView) findViewById(R.id.textView); if (bluetoothAdapter != null && !bluetoothAdapter.isEnabled()) < Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT); >> public void Start_Server(View view) < AcceptThread accept = new AcceptThread(); accept.start(); >private class AcceptThread extends Thread < // The local server socket private final BluetoothServerSocket mmServerSocket; public AcceptThread()< BluetoothServerSocket tmp = null ; // Create a new listening server socket try< tmp = bluetoothAdapter.listenUsingInsecureRfcommWithServiceRecord("appname", MY_UUID_INSECURE); Log.d(TAG, "AcceptThread: Setting up Server using: " + MY_UUID_INSECURE); >catch (IOException e) < Log.e(TAG, "AcceptThread: IOException: " + e.getMessage() ); >mmServerSocket = tmp; > public void run()< Log.d(TAG, "run: AcceptThread Running."); BluetoothSocket socket = null; try< // This is a blocking call and will only return on a // successful connection or an exception Log.d(TAG, "run: RFCOM server socket start. "); socket = mmServerSocket.accept(); Log.d(TAG, "run: RFCOM server socket accepted connection."); >catch (IOException e) < Log.e(TAG, "AcceptThread: IOException: " + e.getMessage() ); >//talk about this is in the 3rd if(socket != null) < connected(socket); >Log.i(TAG, "END mAcceptThread "); > public void cancel() < Log.d(TAG, "cancel: Canceling AcceptThread."); try < mmServerSocket.close(); >catch (IOException e) < Log.e(TAG, "cancel: Close of AcceptThread ServerSocket failed. " + e.getMessage() ); >> > 

ACTIVITY_MAIN.XML

Читайте также:  Set bluetooth on computer

Источник

Оцените статью
Adblock
detector