Android bluetooth serial port

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Bluetooth Serial Port Profile which comfortable to developer application to communication with microcontroller via bluetooth

kiwiai/Android-BluetoothSPP

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

BluetoothSPP Library

Bluetooth Serial Port Profile which comfortable to developer application to communication with microcontroller or android device via bluetooth.

This libraly include all important methods for serial port profile on bluetooth communication. It has built-in bluetooth device list.

• Solve the lack of data like as «abcdefg» which divided to «abc» and «defg» when receive these data

• Auto add LF (0x0A) and CR (0x0D) when send data to connection device

• No need to create layout for bluetooth device list to select device for connection. You can use built-in layout in this library and you can customize layout if you want

• Auto connection supported

• Listener for receive data from connection device

• Import this library to your workspace and include in to your android project

• Declare permission for library

uses-permission android:name="android.permission.BLUETOOTH" /> uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />

• Declare BluetoothSPP like this

BluetoothSPP bt = new BluetoothSPP(Context);

• Check if bluetooth is now available

if(!bt.isBluetoothAvailable()) < // any command for bluetooth is not available >

• Check if bluetooth is not enable when activity is onStart

public void onStart() < super.onStart(); if(!bt.isBluetoothEnable()) < // Do somthing if bluetooth is disable > else < // Do something if bluetooth is already enable > >

• if bluetooth is ready call this method to start service

For connection with android device

bt.startService(BluetoothState.DEVICE_ANDROID);

Communicate with android

For connection with any microcontroller which communication with bluetooth serial port profile module

bt.startService(BluetoothState.DEVICE_OTHER);

Communicate with microcontroller

Bluetooth module with SPP

• Intent to choose device activity

Intent intent = new Intent(getApplicationContext(), DeviceList.class); startActivityForResult(intent, BluetoothState.REQUEST_CONNECT_DEVICE);

don’t forget declare library activty like this

activity android:name="app.akexorcist.bluetoothspp.DeviceList" />

• After intent to choose device activity and finish that activity. You need to check result data on onActivityResult

public void onActivityResult(int requestCode, int resultCode, Intent data) < if(requestCode == BluetoothState.REQUEST_CONNECT_DEVICE) < if(resultCode == Activity.RESULT_OK) bt.connect(data); > else if(requestCode == BluetoothState.REQUEST_ENABLE_BT) < if(resultCode == Activity.RESULT_OK) < bt.setupService(); bt.startService(BluetoothState.DEVICE_ANDROID); setup(); > else < // Do something if user doesn't choose any device (Pressed back) > > >

• If you want to send any data

Читайте также:  Как включить bluetooth ноутбуке

• Listener for data receiving

bt.setOnDataReceivedListener(new OnDataReceivedListener() < public void onDataReceived(byte[] data, String message) < // Do something when data incoming > >);

• Listener for bluetooth connection atatus

bt.setBluetoothConnectionListener(new BluetoothConnectionListener() < public void onDeviceConnected(String name, String address) < // Do something when successfully connected > public void onDeviceDisconnected() < // Do something when connection was disconnected > public void onDeviceConnectionFailed() < // Do something when connection failed > >);

• Listener when bluetooth connection has changed

bt.setBluetoothStateListener(new BluetoothStateListener() < public void onServiceStateChanged(int state) < if(state == BluetoothState.STATE_CONNECTED) // Do something when successfully connected else if(state == BluetoothState.STATE_CONNECTING) // Do something while connecting else if(state == BluetoothState.STATE_LISTEN) // Do something when device is waiting for connection else if(state == BluetoothState.STATE_NONE) // Do something when device don't have any connection > >);
bt.autoConnect("Keyword for filter paired device");

• Listener for auto connection

bt.setAutoConnectionListener(new AutoConnectionListener() < public void onNewConnection(String name, String address) < // Do something when earching for new connection device > public void onAutoConnectionStarted() < // Do something when auto connection has started > >);

• Customize device list’s layout by create layout which include

list view with id name = «list_devices»

button with id name = «button_scan»

xml version="1.0" encoding="utf-8"?> RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="#FDE182" > ListView android:id="@+id/list_devices" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_marginLeft="20dp" android:layout_marginRight="20dp" android:layout_marginTop="20dp" android:smoothScrollbar="true" /> Button android:id="@+id/button_scan" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:layout_alignParentTop="true" android:padding="20dp" android:background="#FFC600" android:text="SCAN" android:textSize="25sp" android:textColor="#7A481B" android:textStyle="bold" /> RelativeLayout>

Custom Device List Layout

But if you don’t need to create layout file. You just want to change only text on device list layout. You can use bundle to change text on device list

Custom Device List Text

Custom Device List Text

Custom Device List Text

Custom Device List Text

Intent intent = new Intent(getApplicationContext(), DeviceList.class); intent.putExtra("bluetooth_devices", "Bluetooth devices"); intent.putExtra("no_devices_found", "No device"); intent.putExtra("scanning", "กำลังทำการค้นหา"); intent.putExtra("scan_for_devices", "Search"); intent.putExtra("select_device", "Select"); startActivityForResult(intent, BluetoothState.REQUEST_CONNECT_DEVICE);

Custom Device List Text

Copyright (c) 2014 Akexorcist

Licensed under the Apache License, Version 2.0 (the «License»); you may not use this file except in compliance with the License. You may obtain a copy of the License at

Читайте также:  Периферийные устройства блютуз не найдены

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an «AS IS» BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

About

Bluetooth Serial Port Profile which comfortable to developer application to communication with microcontroller via bluetooth

Источник

Обмен данными Bluetooth

Пример обмена данными Bluetooth

Продолжаем предыдущую статью о работе с Bluetooth в Android Studio. В этой статье рассмотрим обмен данными Bluetooth, через SPP профиль.

Профиль SPP (Serial Port Profile) – предназначен для обмена данными по Bluetooth. SPP профиль дает возможность, соединить два устройства Bluetooth на транспортном уровне. При таком соединении одно из устройств станет мастером, а второе ведомым. На самом деле нам это не так важно, так как все тонкости скрыты разработчиками классов java. Единственное что нам надо запомнить, это то, что SPP профиль, основан на базовом профиле RFCOM.

SPP профиль Bluetooth

После того как мы обнаружили наше устройство и произвели сопряжение. Нам необходимо создать и открыть сокет.

Для создания сокета воспользуемся следующей командой:

device.createInsecureRfcommSocketToServiceRecord(MY_UUID);

device — это наше устройство Bluetooth.

MY_UUID – uuid SPP профиля.

Внимание!
UUID профиля «00001101-0000-1000-8000-00805f9b34fb»

После создания сокета нам необходимо создать подключение командой connect :

Внимание!
Будьте внимательны при использовании метода connect , он блокирует программу, пока не будет установлено соединение или пока не закончится таймаут. Рекомендуется использовать отдельный поток.

Обмен данными Bluetooth: InputStream

Входящим потоком данных в java является InputStream . В java есть два типа потоков, символьный и байтовый потоки. Что бы инициализировать байтовый поток Input, необходимо применить метод сокета:

Обмен данными Bluetooth: OutputStream

Исходящим потоком данных в java является OutputStream . Что бы инициализировать байтовый поток Otput, необходимо применить метод сокета:

Android studio: пример обмена по bluetooth

Создадим новый класс для обмена данными по Bluetooth. Класс наследуем от класса реализующего потоки.

private class ConnectThread extends Thread < private BluetoothSocket mmSocket = null; private boolean isUpdateDate = false; private final Activity mmActivity; private BluetoothAdapter mmAdapter = null; private OutputStream outData = null; private final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb"); public ConnectThread(BluetoothDevice device, BluetoothAdapter adapter, Activity activity) < BluetoothSocket tmp = null; mmAdapter = adapter; mmActivity = activity; try < if (ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) < return; >//device.getUuids()[0].getUuid() tmp = device.createInsecureRfcommSocketToServiceRecord(MY_UUID); Log.e("TODO", "Сокет создан"); > catch (IOException e) < Log.e("TODO", "Ошибка созадания сокета"); >mmSocket = tmp; > public void setIsUpdate(Boolean data) < isUpdateDate = data; >public void run() < while (isUpdateDate) < if (mServiceBound) < sendData(latitudeToSend + " " + longitudeToSend); try < Thread.sleep(1000); >catch (InterruptedException e) < e.printStackTrace(); >> > > public void connectSSP() < if (ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.BLUETOOTH_SCAN) != PackageManager.PERMISSION_GRANTED) < return; >mmAdapter.cancelDiscovery(); Log.e("TODO", "Завершил поиск даже если небыл включен"); try < Log.e("TODO", "Включаю сокет"); mmSocket.connect(); outData = mmSocket.getOutputStream(); InputStream inData = mmSocket.getInputStream(); AlertDialog dialog = DialogView.getDialog(mmActivity, DialogView.IDD_INFO_CONNECT); dialog.show(); >catch (IOException connectException) < Log.e("TODO", "Не могу подключить SPP", connectException); try < mmSocket.close(); >catch (IOException closeException) < Log.e("TAG", "Не могу закрыть сокет", closeException); >> > public void sendData(String dataStr) < if (isUpdateDate) < try < outData = mmSocket.getOutputStream(); >catch (IOException e) < Log.d("Error", "SSP OUT", e); >byte[] msgBuf = dataStr.getBytes(); try < outData.write(msgBuf); >catch (IOException e) < Log.d("Error", "SSP OUT", e); >> > public void cancel() < try < if (mmSocket != null) < if (mmSocket.isConnected()) mmSocket.close(); >> catch (IOException e) < Log.e("TAG", "Не могу закрыть сокет", e); >//Закрываем поток ConnectThread.interrupted(); > >

Пояснения к коду обмена данными по Bluetooth

При инициализации класса в конструктор класса необходимо передать наше устройство Bluetooth (устройство с которым будем обмениваться данными) и наш Bluetooth adapter (физический блютуз).

Читайте также:  Android connect bluetoothsocket bluetooth

Метод класса setIsUpdate , позволяет установить флаг, для старта передачи данных, если флаг не установлен, то передача не идет.

Метод connectSSP реализует соединение с устройством Bluetooth через профиль SPP. После установки соединения пользователь получит диалоговое сообщение о успешном соединении.

sendData метод класса, который принимает на вход строку для отправки другому устройству. Затем эта строка конвертируется в массив байт и отправляется на передачу.

Последний метод cancel . Данный метод необходимо применять, когда мы завершаем работу с сокетом.

Чтобы начать работу с классом, необходимо из основного активити создать объект класса и вызвать метод Start .

ConnectThread connectBLE = new ConnectThread(btConnectDevice, mAdapter, MainActivity.this); connectBLE.start();

Источник

How to receive serial data using android bluetooth

I am new to android. I am designing an android application that receives serial data from a hardware device through bluetooth. I am working on Htc desire S. I used the sample Bluetooth chat code to receive data. But the data received is incorrect. It misses some values. Can anyone please provide me any other sample code to receive large amount of data through bluetooth and save it in a file.

5 Answers 5

package Android.Arduino.Bluetooth; import android.app.Activity; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothSocket; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.view.View; import android.widget.TextView; import android.widget.EditText; import android.widget.Button; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Set; import java.util.UUID; public class MainActivity extends Activity < TextView myLabel; EditText myTextbox; BluetoothAdapter mBluetoothAdapter; BluetoothSocket mmSocket; BluetoothDevice mmDevice; OutputStream mmOutputStream; InputStream mmInputStream; Thread workerThread; byte[] readBuffer; int readBufferPosition; int counter; volatile boolean stopWorker; @Override public void onCreate(Bundle savedInstanceState) < super.onCreate(savedInstanceState); setContentView(R.layout.main); Button openButton = (Button)findViewById(R.id.open); Button sendButton = (Button)findViewById(R.id.send); Button closeButton = (Button)findViewById(R.id.close); myLabel = (TextView)findViewById(R.id.label); myTextbox = (EditText)findViewById(R.id.entry); //Open Button openButton.setOnClickListener(new View.OnClickListener() < public void onClick(View v) < try < findBT(); openBT(); >catch (IOException ex) < >> >); //Send Button sendButton.setOnClickListener(new View.OnClickListener() < public void onClick(View v) < try < sendData(); >catch (IOException ex) < >> >); //Close button closeButton.setOnClickListener(new View.OnClickListener() < public void onClick(View v) < try < closeBT(); >catch (IOException ex) < >> >); > void findBT() < mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if(mBluetoothAdapter == null) < myLabel.setText("No bluetooth adapter available"); >if(!mBluetoothAdapter.isEnabled()) < Intent enableBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableBluetooth, 0); >Set pairedDevices = mBluetoothAdapter.getBondedDevices(); if(pairedDevices.size() > 0) < for(BluetoothDevice device : pairedDevices) < if(device.getName().equals("MattsBlueTooth")) < mmDevice = device; break; >> > myLabel.setText("Bluetooth Device Found"); > void openBT() throws IOException < UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); //Standard SerialPortService ID mmSocket = mmDevice.createRfcommSocketToServiceRecord(uuid); mmSocket.connect(); mmOutputStream = mmSocket.getOutputStream(); mmInputStream = mmSocket.getInputStream(); beginListenForData(); myLabel.setText("Bluetooth Opened"); >void beginListenForData() < final Handler handler = new Handler(); final byte delimiter = 10; //This is the ASCII code for a newline character stopWorker = false; readBufferPosition = 0; readBuffer = new byte[1024]; workerThread = new Thread(new Runnable() < public void run() < while(!Thread.currentThread().isInterrupted() && !stopWorker) < try < int bytesAvailable = mmInputStream.available(); if(bytesAvailable >0) < byte[] packetBytes = new byte[bytesAvailable]; mmInputStream.read(packetBytes); for(int i=0;i>); > else < readBuffer[readBufferPosition++] = b; >> > > catch (IOException ex) < stopWorker = true; >> > >); workerThread.start(); > void sendData() throws IOException < String msg = myTextbox.getText().toString(); msg += "\n"; mmOutputStream.write(msg.getBytes()); myLabel.setText("Data Sent"); >void closeBT() throws IOException < stopWorker = true; mmOutputStream.close(); mmInputStream.close(); mmSocket.close(); myLabel.setText("Bluetooth Closed"); >> 

Here for Manifest: add to Application

// permission must be enabled complete    

Источник

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