• Stars
    star
    188
  • Rank 205,522 (Top 5 %)
  • Language
    Java
  • Created over 8 years ago
  • Updated over 4 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Bluetooth client library for Android.

Android Bluetooth Client Library Download

This is an Android library that simplifies the process of bluetooth communication, client side.

This library does not support BLE devices;

Install

Add to your gradle dependencies:

implementation 'me.aflak.libraries:bluetooth:1.3.9'

Enable bluetooth

Careful: You also have to enable phone location in newer versions of Android.

Asking user for bluetooth activation

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    // ...
    // Need to ask for bluetooth permissions before calling constructor !
    // Permissions are {BLUETOOTH, BLUETOOTH_ADMIN, ACCESS_COARSE_LOCATION}
    bluetooth = new Bluetooth(this);
    bluetooth.setBluetoothCallback(bluetoothCallback);
}

@Override
protected void onStart() {
    super.onStart();
    bluetooth.onStart();
    if(bluetooth.isEnabled()){
        // doStuffWhenBluetoothOn() ...
    } else {
        bluetooth.showEnableDialog(ScanActivity.this);
    }
}

@Override
protected void onStop() {
    super.onStop();
    bluetooth.onStop();
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    bluetooth.onActivityResult(requestCode, resultCode);
}

private BluetoothCallback bluetoothCallback = new BluetoothCallback() {
    @Override public void onBluetoothTurningOn() {}
    @Override public void onBluetoothTurningOff() {}
    @Override public void onBluetoothOff() {}

    @Override
    public void onBluetoothOn() {
        // doStuffWhenBluetoothOn() ...
    }

    @Override
    public void onUserDeniedActivation() {
        // handle activation denial...
    }
};

Without asking user for bluetooth activation

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    // ...
    // Need to ask for bluetooth permissions before calling constructor !
    // Permissions are {BLUETOOTH, BLUETOOTH_ADMIN, ACCESS_COARSE_LOCATION}
    bluetooth = new Bluetooth(this);
    bluetooth.setBluetoothCallback(bluetoothCallback);
}

@Override
protected void onStart() {
    super.onStart();
    bluetooth.onStart();
    if(bluetooth.isEnabled()){
        // doStuffWhenBluetoothOn() ...
    } else {
        bluetooth.enable()
    }
}

@Override
protected void onStop() {
    super.onStop();
    bluetooth.onStop();
}

private BluetoothCallback bluetoothCallback = new BluetoothCallback() {
    @Override public void onBluetoothTurningOn() {}
    @Override public void onBluetoothTurningOff() {}
    @Override public void onBluetoothOff() {}
    @Override public void onUserDeniedActivation() {}
    
    @Override
    public void onBluetoothOn() {
        // doStuffWhenBluetoothOn() ...
    }
};

Discover devices and pair

Listener

bluetooth.setDiscoveryCallback(new DiscoveryCallback() {
    @Override public void onDiscoveryStarted() {}
    @Override public void onDiscoveryFinished() {}
    @Override public void onDeviceFound(BluetoothDevice device) {}
    @Override public void onDevicePaired(BluetoothDevice device) {}
    @Override public void onDeviceUnpaired(BluetoothDevice device) {}
    @Override public void onError(String message) {}
});

Scan and Pair

bluetooth.startScanning();
bluetooth.pair(device);
bluetooth.pair(device, "optional pin");

Get paired devices

List<BluetoothDevice> devices = bluetooth.getPairedDevices();

Connect to device and communicate

Listener

bluetooth.setDeviceCallback(new DeviceCallback() {
    @Override public void onDeviceConnected(BluetoothDevice device) {}
    @Override public void onDeviceDisconnected(BluetoothDevice device, String message) {}
    @Override public void onMessage(byte[] message) {}
    @Override public void onError(String message) {}
    @Override public void onConnectError(BluetoothDevice device, String message) {}
});

Connect to device

// three options
bluetooth.connectToName("name");
bluetooth.connectToAddress("address");
bluetooth.connectToDevice(device);

Connect to device using port trick

See this post for details: https://stackoverflow.com/a/25647197/5552022

bluetooth.connectToNameWithPortTrick("name");
bluetooth.connectToAddressWithPortTrick("address");
bluetooth.connectToDeviceWithPortTrick(device);

Should be avoided

Send a message

bluetooth.send("hello, world");
bluetooth.send(new byte[]{61, 62, 63});

Receive messages

The default behavior of the library is the read from the input stream until it hits a new line, it will then propagate the message through listeners as a byte array. You can change the way the library reads from the socket by creating your own reader class. It must extend from SocketReader and you should override the byte[] read() throws IOException method. This method must block. It should not return if no values were received.

The default behavior is actually one example of implementation :

public class LineReader extends SocketReader{
    private BufferedReader reader;

    public LineReader(InputStream inputStream) {
        super(inputStream);
        reader = new BufferedReader(new InputStreamReader(inputStream));
    }

    @Override
    public byte[] read() throws IOException {
        return reader.readLine().getBytes();
    }
}

This is an implementation for a custom delimiter :

public class DelimiterReader extends SocketReader {
    private PushbackInputStream reader;
    private byte delimiter;

    public DelimiterReader(InputStream inputStream) {
        super(inputStream);
        reader = new PushbackInputStream(inputStream);
        delimiter = 0;
    }

    @Override
    public byte[] read() throws IOException {
        List<Byte> byteList = new ArrayList<>();
        byte[] tmp = new byte[1];

        while(true) {
            int n = reader.read();
            reader.unread(n);

            int count = reader.read(tmp);
            if(count > 0) {
                if(tmp[0] == delimiter){
                    byte[] returnBytes = new byte[byteList.size()];
                    for(int i=0 ; i<byteList.size() ; i++){
                        returnBytes[i] = byteList.get(i);
                    }
                    return returnBytes;
                } else {
                    byteList.add(tmp[0]);
                }
            }
        }
    }
}

Then you can use your reader :

bluetooth.setReader(LineReader.class);

JavaDoc

JavaDoc is in doc folder.

Example Code

app module

Download Demo App

Get it on Google Play

License

MIT License

Copyright (c) 2017 Michel Omar Aflak

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

More Repositories

1

Medium-Python-Neural-Network

This code is part of my post on Medium.
Python
92
star
2

Arduino-Library

A lightweight Android library to communicate with Arduino through usb.
Java
81
star
3

Fingerprint

Android library that simplifies the process of fingerprint authentications.
Java
68
star
4

Android-Camera2-Library

Library to use Android Camera2 api easily.
Java
68
star
5

Keras-Android-XOR

How to run a Keras model on Android using Tensorflow API.
Java
32
star
6

Asynchronous-Socket-Class-C-Windows

SocketClient allows easy communication between sockets and implements a callback pattern for receiving messages!
C++
31
star
7

Bluetooth-Terminal

Source code of my application "Bluetooth Terminal" on the playstore.
Java
30
star
8

Matrix

Matrix class in C++ with operators implemented.
C++
22
star
9

Dagger2-CYS

This code is part of a tutorial about Dagger2 on https://causeyourestuck.io
Java
19
star
10

HC-SR04-Raspberry-Pi-C-

This class allows you to get datas from the HC-SR04 sensor easily in C++!
C++
18
star
11

first-neural-network

Simple neural network implemented from scratch in C++.
C++
18
star
12

APDU-Library

Library built on top of libNfc to easily send APDU commands.
C++
16
star
13

Async-Socket

Asynchronous socket class implemented in C++ for Linux systems.
C++
16
star
14

python-neural-networks

A Neural Network library coded from scratch.
Python
13
star
15

Dagger2-Sample

Very simple example to use Dagger 2
Java
13
star
16

Filter-Library

Android library to filter any object in a list using a simple annotation.
Java
12
star
17

RayTracer-Kotlin

Simple ray tracer.
Kotlin
12
star
18

Room-Dagger2-Sample

Simple example to illustrate the use of Room combined with Dagger2.
Java
11
star
19

ERC4671

Non-Tradable Tokens Standard
Solidity
10
star
20

Dagger2-MVP

Login page using Dagger2 and MVP architecture.
Java
9
star
21

Reinforcement-Learning-CPP

Reinforcement Learning algorithm from scratch in C++.
C++
8
star
22

Bluetooth-Android

This is an android class that allows you to communicate simply using a bluetooth connection.
Java
8
star
23

kmedoids

KMedoids algorithm.
Python
7
star
24

mct-to-libnfc

Dump converter between mifare classic tool and libnfc formats.
C++
7
star
25

Youtube-Video-Downloader

Chrome Extension & local server to download youtube videos easily.
Python
5
star
26

neglnn

Not Efficient but Great to Learn Neural Network
Python
5
star
27

autocolab

Launch colab file in a headless browser.
Python
5
star
28

cpp-neural-network

Neural Network from scratch in C++.
C++
4
star
29

Youtube-Python-Neural-Network

Code for my youtube video "Neural Network from Scratch | Mathematics & Python Code"
Python
4
star
30

RayTracer-CPP

Simple ray tracer in C++.
C++
4
star
31

Annotation-Processor-Sample

Simple example to illustrate the use of android annotation and annotation processor.
Java
4
star
32

Musipy

NodeJs server using omxplayer to play song from an external app.
JavaScript
3
star
33

Automatic-Differentiation

Simple automatic differentiation tool.
C++
3
star
34

neglnn2

NEGLNN 2 - Computation Graph
Python
3
star
35

MNIST-Keras-Android

Running Keras CNN model on Android.
Java
2
star
36

Firebase-Chat

A very simple one page Android chat using Firebase !
Java
2
star
37

gesture_recognition

Python
2
star
38

Firebase-Secure-Chat

This is an example of how to use FirebaseAuth within an Android chat!
Java
2
star
39

CV

Curriculum Vitae.
TeX
2
star
40

MCMC

Markov Chain Monte Carlo
Python
2
star
41

GY-521-Raspberry-Pi-C-

This class allows you to get datas from the GY-521 sensor on Raspberry Pi AND in C++ !
C++
2
star
42

wave_function_collapse

Wave Function Collapse Algorithm
Python
2
star
43

autodiff

Reverse mode automatic differentiation.
C++
1
star
44

Fourier-Animation

Fourier Drawing Animation
Python
1
star
45

huffman-coding

Huffman coding
Python
1
star
46

ETH-Widget-Android

ETH widget for Android. Price pulled from coinmarketcap.com.
Java
1
star
47

Image-Kernel-Convolution

Program to apply filters of your choice to images easily.
Java
1
star
48

Arduino-USB

Arduino USB app code
Java
1
star
49

wordle

Wordle solver
Python
1
star
50

quadtree

QuadTree library for Python
Python
1
star
51

FrozenLake-QLearning

Resolving the FrozenLake problem from OpenAI Gym.
Python
1
star
52

gmake2

Makefile generator v2.
C++
1
star
53

matlab-neural-network

Neural Network implemented with Matlab.
MATLAB
1
star
54

QNetwork-Keras

QNetwork implemented with Keras
Python
1
star
55

gender-prediction

Name to Gender prediction. Trained on French names.
Python
1
star
56

graphql-mongodb

Simple server using GraphQL and MongoDB
JavaScript
1
star
57

EZSocket

Simple class for TCP/IP Socket communications
Java
1
star