Giter Site home page Giter Site logo

bluetooth-library's Introduction

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.

bluetooth-library's People

Contributors

johannesdev avatar mansya avatar omaraflak avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

bluetooth-library's Issues

onMessage method is not calling after device sending data to application

Hello team,

I have implemented this library for sharing data.
but after sending data to device :

String s = "*" +"Log_Interval," + selectedValue + "," + "&";
bluetooth.send(s);

its properly sending data to that device but after device responds with success but not getting to our application (onMessage or onError method is not calling)

please help me to identify this issue what actually I did mistake in my code while using library

AutoConnect Error

Hi,
I am trying to use the auto connect feature but every time I try to connect it shows devive name mismatch.

Thanks

Keep connection between activities?

Hi, I've been trying your library and works great, but I was wondering if it's possible to pass the connection between activites avoiding to reconnect everytime I change from activity? And if it's possible, how?

Bluetooth connection issues

I'm having some issues connecting to Bluetooth devices.
When I connect, the onError() callback is called with error message: read failed, socket might closed or timeout, read ret: -1. I did a little bit of exploring into this issue, and it seems like creating an insecure connection would fix things (https://stackoverflow.com/a/36786031/4779937). Would you be able to add a toggle option for Secure / Insecure connect thread in your ConnectThread class?

If you'd like source code for the bug I'm getting, let me know.

connection error

after pairing device successfully, unable to connect to device, error comes: read failed, socket might closed or timeout, read ret: -1.

after paired how can i send message to paired device?

add a discoverycallback.onDiscoveryStartedListener()

this maybe irrelevant or I might have not checked it thoroughly, but there is not a receiver or listener for ACTION_DISCOVERY_STARTED.
it might not be much useful, but sometimes there are cases where one could use a listener for this. for example , if I write bluetoothObj.startScanning() in my onCreate(), but want to handle a rotating circle animation on the starting of scanning I would prefer writing the code in the same place where i have written the code for stopping such animation,i.e my interface's object.

I would like to create a pull request for it.

(And by the way, a big thanks for creating this amazing library, it helped me understand the basic working of blue-tooth :))

BluetoothServerSocket

Hi!
Does this library implements BluetoothServerSocket?
Because I am trying to create application which would send each other messages, but I have issue with bluetooth.connectToDevice().
I think is could be issue with BluetoothServerSocket.

About scanning the nearby bluetooth device

Hey, I try to use your library to connect Android and Arduino. I am able to connect already paired device and also able to send and receive data between Android and Arduino. But facing problem to scan nearby device and list it. Even the progress bar is simply rotating not working the function setProgressAndState(). My keen guess is
private DiscoveryCallback discoveryCallback = new DiscoveryCallback() {......}
is not working or when the scan button is pressed, the DiscoveryCallback is not calling.
I followed the code as it is in the link mentioned below
https://github.com/OmarAflak/Bluetooth-Library/blob/master/app/src/main/java/me/aflak/libraries/ScanActivity.java

startDiscovery impossible

Hello

i try to use your library with a simple code
bluetooth = new Bluetooth(this);

    bluetooth.setBluetoothCallback(bluetoothCallback);
    bluetooth.setDiscoveryCallback(discoveryCallback);

    if(bluetooth != null) {
        try {
            bluetooth.startScanning();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

but i have this error

java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.bluetooth.BluetoothAdapter.startDiscovery()' on a null object reference

Receiver never unregister

I'm trying to implement in many activity but have a problem, the coneccion never close and i receiver after back (i tested to change the onStart to onResume and onStop to onPause) and this block the connexion in the second activity (the socket it's allways bussy after the first connexion)

Activity

public class TestActivity extends AppCompatActivity implements TestView {
...
 @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
      
        DaggerPesosComponent.builder()
                .bluetoothModule(MyApp.getInstance().bluetoothModule())
                .pesosModule(new TestModule(this))
                .build().inject(this);
...

 @Override
    protected void onStart() {
        super.onStart();
        presenter.onStart(this);
    }

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

Presenter

 @Override
        public void onMessage(String message) {
            Log.i("DATA", message);
        }
@Override
    public void onStart(Activity activity) {
        interactor.onStart(bluetoothCallback, activity);
        if (interactor.isBluetoothEnabled()) {
            interactor.connectToDevice(device, communicationCallback);
            view.setStatus(R.string.bluetooth_connecting);
        } else {
            interactor.enableBluetooth();
        }
    }


    @Override
    public void onStop() {

        handler.removeCallbacks(runnable);
        interactor.onStop();
        communicationCallback = null;

    }

Interactor

@Override
    public void onStart(BluetoothCallback bluetoothCallback, Activity activity) {
        bluetooth.onStart();
        bluetooth.setCallbackOnUI(activity);
        bluetooth.setBluetoothCallback(bluetoothCallback);
    }

    @Override
    public void onStop() {
        bluetooth.onStop();
    }

connection error

Everytime I try to connect to a device i get:

error_read failed, socket might closed or timeout, read ret: -1

Any idea?

Bluetooth usage from background service.

This isn't an issue - you may want to move it somewhere else.

I have a server-client system used for FRC Robotics competitions for syncing data using your library (great library by the way). The server is constantly listening, and will automatically process some stuff if a client tries to connect. Is it possible to use your Bluetooth library from a background service instead of having it within an activity?

Attempt to invoke virtual method 'android.bluetooth.BluetoothSocket me.aflak.bluetooth.Bluetooth$ReceiveThread.getSocket()' on a null object reference

Hi @omaraflak , I am seeing an error when trying to use bluetooth.getSocket() after successfully connecting, I keep getting the following error:

W/System.err: java.lang.NullPointerException: Attempt to invoke virtual method 'android.bluetooth.BluetoothSocket me.aflak.bluetooth.Bluetooth$ReceiveThread.getSocket()' on a null object reference
        at me.aflak.bluetooth.Bluetooth.getSocket(Bluetooth.java:144)
        at com.scout.eurobeatandroid.MainActivity$9.onDeviceConnected(MainActivity.java:207)
        at me.aflak.bluetooth.Bluetooth$6$1.run(Bluetooth.java:485)
        at me.aflak.bluetooth.utils.ThreadHelper.run(ThreadHelper.java:15)
        at me.aflak.bluetooth.Bluetooth$6.run(Bluetooth.java:482)
07-06 21:15:10.697 7745-7795/com.scout.ccc W/System.err:     at java.lang.Thread.run(Thread.java:764)

I have have copied the code examples correctly, so i'm not sure if there is an issue with the method, or I am doing something wrong.

// CONNECTION
private void connect(String name) {
     Toast.makeText(getApplicationContext(),"Attempting to Connect to " + name, Toast.LENGTH_SHORT).show();
     bluetooth.connectToName(name);
}

// ON DEVICE CONNECTION CALLBACK
      bluetooth.setDeviceCallback(new DeviceCallback() {
            @Override public void onDeviceConnected(BluetoothDevice device) {
                runOnUiThread(new Runnable() {public void run() {final Toast toast = Toast.makeText(getApplicationContext(), "Connected to OBD-II", Toast.LENGTH_SHORT);
                    toast.show();
                    bluetoothPairedList.setVisibility(View.GONE);
                }});

                // setup OBD-11 params
                BluetoothSocket socket = bluetooth.getSocket(); // NULL POINTER EXCEPTION HERE

                try {
                    new EchoOffCommand().run(socket.getInputStream(), socket.getOutputStream());
                    new LineFeedOffCommand().run(socket.getInputStream(), socket.getOutputStream());
                    new TimeoutCommand(125).run(socket.getInputStream(), socket.getOutputStream());
                    new SelectProtocolCommand(ObdProtocols.AUTO).run(socket.getInputStream(), socket.getOutputStream());
                } catch (final Exception e) {
                    // handle errors
                    e.printStackTrace();
                }
            }

...

}

Thanks for taking a look.

function request: isScanning()

Hi. I really feel this library has the potential to be used as a simple wrapper around Android's Bluetooth class(even maybe as a default in android libraries 😃 )
So here is a function request

    public boolean isScanning(){
               return bluetoothAdapter.isDiscovering();
    }

Sometimes the dev might want to restrict his app's user from pressing the "Scan" button again and again and to do so, he may want a checker function to do so.And since this is a great wrapper class around defaullt bluetooth, why not provide the dev with all the possible tools?

Thanks,
Ansh

Sending raw buffer (0 - 255)

Hello!

I need to send over bluetooth spp raw buffer (variables with value range: 0 - 255). Is this possible? I was looking for some method like "bluetooth.write(buffer, len)", but nothing to found...

Best regards!
Patryk

IOException: read failed, socket might closed - Bluetooth on Android 4.3

I have this problem and I found a fix on stackoverflow

The problem is with the socket.mPort parameter. When you create your socket using socket = device.createRfcommSocketToServiceRecord(SERIAL_UUID); , the mPort gets integer value "-1", and this value seems doesn't work for android >=4.2 , so you need to set it to "1".

try {
           socket.connect();
           Log.e("","Connected");
    } catch (IOException e) {
           Log.e("",e.getMessage());
           try {
                    Log.e("","trying fallback...");

                    socket =(BluetoothSocket) device.getClass().getMethod("createRfcommSocket", new Class[] {int.class}).invoke(device,1);
                    socket.connect();

                    Log.e("","Connected");
               } catch (Exception e2) {
                 Log.e("", "Couldn't establish Bluetooth connection!");
               }
     }

so, If you can add this workaround in your library, it will be helpful...

bluetooth version

wich version of bluetooth is this library working with , I didn't see the version in documents

Receive from HC-06

Hi, I want to design an app that receives messages from HC-06 and displays them on my app. Is their any easy way to do that using this library, as it doesnt specify it in README?

Android 9 device not visible in scan

hello
when i scan devices, my smartphone (MIA3, android one) doesn't appears. This device is in visible mode, if i go in the bluetooth parameters of the smartphone and execute a scan, the device is well recognized.

String Translate ...

Hi, Is Possible to Set the Custom String text for the Word : "Scanning...", "Pairing...", "Done" for the layout Id activity_scan_state ?

Many Thank's

"read failed, socket might closed or timeout, read ret: -1"

Hi very cool project thank you for your work, i am trying to connect to a BLE device, and this error occurring

"read failed, socket might closed or timeout, read ret: -1"

i am using the method bluetooth.connectToName(device.getName().toString()); and
bluetooth.connectToDevice(device); gave the same error
i am not sure if this library handle ble communications, this could be the issue? i will able to send messages after getting the connection socket open? i am testing in a Samsung j2 prime android 6.01, by the way until now search device, enable BT, disable BT, and pair method have work fine to me!

function Refactor: startScanning()

I made a special test condition in my app, where the user might accidentally press The button to "start Discovering Nearby Devices" multiple times even when bluetooth is actually off.Although the app or the library isn't generating errors,but is also not showing any perticular changes to repeated calls in the logs.

however I made the test case a little more tricky by doing this : updated the button for "start scanning" , which will now alter its text between "scanning started" and "stop scanning" on repeated presses(WITHOUT checking for bluetooth being enable or not).
thus , the library failed(not generating errors but also not showing changes) on repeated presses since the startScanning() function was of void return-type, so their was no way to check if the scanning has started or not . it was still showing "scanning started" on repeated presses since the scan has not started on the first place!and am pretty sure that bluetoothAdapter.startDiscovery() is being uselessly called again and again by the library

you see, its not a 2 case flag, its a 3-case flag:
if( discovery is not started)=>
Boolean isStarted= CALL startDiscovery() which will return weather discovery started
successfully or failed;
return isStarted; //so that user can implement changes/ handle errors for startDiscovery() call

else(if discovery is started)=>
stopDiscovery()// I will feel nice if this function also returned a boolean too

again, its not a very high profile error, since startScanning() is almost always a background function invisible to user , so there is almost a null chance for user to create errors in this but as i said in my other issue raise, i see a simple and nice stock library in this code, so you might or might not wanna change it

 public boolean startScanning(){
        IntentFilter filter = new IntentFilter();
        filter.addAction(BluetoothDevice.ACTION_FOUND);
        filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);

        context.registerReceiver(scanReceiver, filter);
        Boolean hasDiscoveryStarted =bluetoothAdapter.startDiscovery();
        return hasDiscoveryStarted;
    }

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void java.io.OutputStream.write(byte[])' on a null object reference

Hi
Firstly thank you for this awesome and life saving library. I am just trying to send data through bluetooth but it just give me this error.

03-12 17:58:56.029 22414-22414/? E/AndroidRuntime: FATAL EXCEPTION: main
                                                   Process: com.badarshahzad54.pcbs, PID: 22414
                                                   java.lang.RuntimeException: Error receiving broadcast Intent { act=sendData flg=0x10 (has extras) } in com.badarshahzad54.pcbs.service.SendAndReceive$4@d5fe5e5
                                                       at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:1172)
                                                       at android.os.Handler.handleCallback(Handler.java:836)
                                                       at android.os.Handler.dispatchMessage(Handler.java:103)
                                                       at android.os.Looper.loop(Looper.java:203)
                                                       at android.app.ActivityThread.main(ActivityThread.java:6251)
                                                       at java.lang.reflect.Method.invoke(Native Method)
                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1063)
                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:924)
                                                    Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void java.io.OutputStream.write(byte[])' on a null object reference
                                                       at me.aflak.bluetooth.Bluetooth.send(Bluetooth.java:92)
                                                       at com.badarshahzad54.pcbs.service.SendAndReceive.send(SendAndReceive.java:76)
                                                       at com.badarshahzad54.pcbs.service.SendAndReceive$4.onReceive(SendAndReceive.java:188)
                                                       at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:1162)
                                                       at android.os.Handler.handleCallback(Handler.java:836) 
                                                       at android.os.Handler.dispatchMessage(Handler.java:103) 
                                                       at android.os.Looper.loop(Looper.java:203) 
                                                       at android.app.ActivityThread.main(ActivityThread.java:6251) 
                                                       at java.lang.reflect.Method.invoke(Native Method) 
                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1063) 
                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:924) 

Multiple Clients.

I want to create an Server - Client Android app using Bluetooth can I use this library to develop it?

Can we create an insecure connection with this library ?

I use the following code with native Bluetooth library whenever i need to create an insecure connection with HC-05(a Bluetooth module for Arduino) can I do same with this library?

BA = BluetoothAdapter.getDefaultAdapter();//get the mobile bluetooth device
//connects to the device's MAC_ADDRESS and checks if it's available
BluetoothDevice BD = BA.getRemoteDevice(MAC_ADDRESS);
BS = BD.createInsecureRfcommSocketToServiceRecord(myUUID);
//create a RFCOMM (SPP) connection
BluetoothAdapter.getDefaultAdapter().cancelDiscovery();
BS.connect();

Bluetooth.getDevice is not available in update version

Hi
I updated to the new version and I made changes what you refacter the name of methods. But I found in updated version the Bluetooth object doesn't have .getDevice method. Could you tell me how I can get this method call?

Bluetooth-Library in Service

Hey, first of all, thank you for your great library, I really appreciate all your work.
But I wondered if I could use your library in a service because I need to be able to receive data across multiple activities.
Now when you I try to initialize the Bluetooth object, I need an activity context which I don't have in a service bluetooth = new Bluetooth(?). Apart from that I can't override onStart() or onStop() where I would call bluetooth.onStart()/bluetooth.onStop()

Or is there another simple solution I am just missing without using a service and still be able to receive data across all activities. I look forward to hearing from you

Error in onConnect()

I am sure its my unlucky day, because even after so many changes, my app doesn't seems to be even near to completion. anyways now am using the original library w/o any modifications and having this error on clicking the onConnect():

03-11 19:30:32.211 1747-1747/com.example.android.testing_lib2 E/#####################: getPAIREDrms: paired devlist:[D6:5F:E0:65:82:3B, 31:01:00:00:02:C6, 00:21:13:01:E5:6C]
03-11 19:30:32.212 1747-1747/com.example.android.testing_lib2 E/#####################: getPAIREDrms: paired rms found!!
03-11 19:30:49.338 1747-1892/com.example.android.testing_lib2 E/AndroidRuntime: FATAL EXCEPTION: Thread-7772
Process: com.example.android.testing_lib2, PID: 1747
android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:7085)
at android.view.ViewRootImpl.requestLayout(ViewRootImpl.java:1048)
at android.view.View.requestLayout(View.java:17845)
at android.view.View.requestLayout(View.java:17845)
at android.view.View.requestLayout(View.java:17845)
at android.view.View.requestLayout(View.java:17845)
at android.view.View.requestLayout(View.java:17845)
at android.view.View.requestLayout(View.java:17845)
at android.support.v4.widget.NestedScrollView.requestLayout(NestedScrollView.java:1669)
at android.view.View.requestLayout(View.java:17845)
at android.view.View.requestLayout(View.java:17845)
at android.view.View.requestLayout(View.java:17845)
at android.widget.TextView.checkForRelayout(TextView.java:7159)
at android.widget.TextView.setText(TextView.java:4098)
at android.widget.TextView.setText(TextView.java:3950)
at android.widget.TextView.setText(TextView.java:3925)
at com.example.android.testing_lib2.MainActivity$7.onDeviceConnected(MainActivity.java:233)
at me.aflak.bluetooth.Bluetooth$ConnectThread$1.run(Bluetooth.java:306)
at me.aflak.bluetooth.ThreadHelper.run(ThreadHelper.java:15)
at me.aflak.bluetooth.Bluetooth$ConnectThread.run(Bluetooth.java:303)
03-11 19:30:49.934 1747-1747/com.example.android.testing_lib2 E/ActivityThread: Activity com.example.android.testing_lib2.MainActivity has leaked IntentReceiver me.aflak.bluetooth.Bluetooth$8@94dc88b that was originally registered here. Are you missing a call to unregisterReceiver()?
android.app.IntentReceiverLeaked: Activity com.example.android.testing_lib2.MainActivity has leaked IntentReceiver me.aflak.bluetooth.Bluetooth$8@94dc88b that was originally registered here. Are you missing a call to unregisterReceiver()?
at android.app.LoadedApk$ReceiverDispatcher.(LoadedApk.java:942)
at android.app.LoadedApk.getReceiverDispatcher(LoadedApk.java:713)
at android.app.ContextImpl.registerReceiverInternal(ContextImpl.java:1775)
at android.app.ContextImpl.registerReceiver(ContextImpl.java:1755)
at android.app.ContextImpl.registerReceiver(ContextImpl.java:1749)
at android.content.ContextWrapper.registerReceiver(ContextWrapper.java:489)
at me.aflak.bluetooth.Bluetooth.onStart(Bluetooth.java:65)
at com.example.android.testing_lib2.MainActivity.onCreate(MainActivity.java:41)
at android.app.Activity.performCreate(Activity.java:6100)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1112)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2481)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2614)
at android.app.ActivityThread.access$800(ActivityThread.java:178)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1470)
at android.os.Handler.dispatchMessage(Handler.java:111)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5643)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:960)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)

I am using the following codes to connect to the device:

btConnevtHc05.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View v) {
               bbttManager.stopScanning();
               bbttManager.removeDiscoveryCallback();
               BluetoothDevice dev=getPAIREDrms();
               if(dev!=null) {
                   bbttManager.connectToDevice(dev);
               }
           }
       });
  public BluetoothDevice getPAIREDrms() {
       List<BluetoothDevice> devList=bbttManager.getPairedDevices();
       Log.e(TAG, "getPAIREDrms: paired devlist:"+devList );
       for (BluetoothDevice dev:devList) {
           if( dev.getAddress().equals("00:21:13:01:E5:6C")){
               Log.e(TAG, "getPAIREDrms: paired rms found!!" );
               return dev;

           }

       }
       Log.e(TAG, "getHC05device: no 'PAIRED' hc05 dev found" );
       return null;
   }

can you help me why is this happenning??

Q - Compatibility

Hello, congrats for the nice lib.

Does it works with BLE devices aswell?

Thanks

Can not terminate socket on activity close.

@OverRide
public void onConnect(BluetoothDevice device) {
Display("Connected to "+device.getName()+" - "+device.getAddress());
this.runOnUiThread(new Runnable() {
@OverRide
public void run() {

        }
    });
}

public void Display(final String s){
    this.runOnUiThread(new Runnable() {
        @Override
        public void run() {
            Log.e("Status","------------------------------------------"+s);
        }
    });
}

@Override
public void onDisconnect(BluetoothDevice device, String message) {
    Display("Disconnected!");
    Display("Connecting again...");
    b.connectToDevice(device);
}

@Override
public void onMessage(String message) {

    this.runOnUiThread(new Runnable() {
        @Override
        public void run() {
            String str = message;
            str = str.substring(1,str.length());
            String liter = str.substring(0,3);
            String subleter = str.substring(4,5);
            String lastLeter = liter+"."+subleter;

            Log.e("Message","------------------------------------------"+message);
            if(et_weightHasFocus && message.contains("L"))
                et_weight.setText(lastLeter);
        }
    });

}

@Override
public void onError(String message) {
    Display("Error: "+message);
}

@Override
public void onConnectError(final BluetoothDevice device, String message) {
    Display("Error: "+message);
    Display("Trying again in 3 sec.");
    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            Handler handler = new Handler();
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    b.connectToDevice(device);
                }
            }, 2000);
        }
    });
}

private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
@OverRide
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();

        if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
            final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR);
         //   Intent intent1 = new Intent(Chat.this, Select.class);

            switch (state) {
                case BluetoothAdapter.STATE_OFF:
                    if(registered) {
                        unregisterReceiver(mReceiver);
                        registered=false;
                    }

// startActivity(intent1);
// finish();
break;
case BluetoothAdapter.STATE_TURNING_OFF:
if(registered) {
unregisterReceiver(mReceiver);
registered=false;
}
// startActivity(intent1);
finish();
break;
}
}
}
};

@OverRide
public void onBackPressed() {

    Log.e("register",registered+"");
    if(registered) {
        unregisterReceiver(mReceiver);
        registered=false;
    }



    finish();
}

I have to close the socket because next time i open it, it fails to connect Says Try again in 3 seconds
Need Help

Cannot connect after close an activity and reopen again.

I try reopen activity and connect BT, but it was error:

08-02 07:03:45.892 24983-24992/com.test.bt E/System: Uncaught exception thrown by finalizer
08-02 07:03:45.892 24983-24992/com.test.bt E/System: java.io.IOException: socket not created
        at android.net.LocalSocketImpl.shutdownInput(LocalSocketImpl.java:396)
        at android.net.LocalSocket.shutdownInput(LocalSocket.java:206)
        at android.bluetooth.BluetoothSocket.close(BluetoothSocket.java:582)
        at android.bluetooth.BluetoothSocket.finalize(BluetoothSocket.java:277)
        at java.lang.Daemons$FinalizerDaemon.doFinalize(Daemons.java:228)
        at java.lang.Daemons$FinalizerDaemon.run(Daemons.java:206)
        at java.lang.Thread.run(Thread.java:818)

I must destroy app (not just activity) and reopen app again and launch activity and then it normal. But if i close activity and reopen again it will error.

And also how to stop stream from this libs?

new logo

Hi, I am a graphic designer, I want to help others in graphic design.

After I reviewed your project, I see your logo is very simple and not interesting. Therefore I want to contribute to this project by creating a new logo / icon. what do you think?

Leaked Intent Reciever

Hi,

First of all thank you for you effort in the amazing library. I have no problem using this library on Android API 25 when I load on to Android API 27 I get the following error.

" android.app.IntentReceiverLeaked: Activity com.example.mattd.X.Patient has leaked IntentReceiver me.aflak.bluetooth.Bluetooth$7@7be2431 that was originally registered here. Are you missing a call to unregisterReceiver()?"

This happens when the connection is initiated. I am using a Bluetooth classic device.

Again the application worked fine on android API 25.

Any help would be greatly appreciated.

Cheers,
Matt

Error:multiple broadcasts recieved for same device onStartScanning()

don't know if this is a flaw on my app's side or the library side, but here are the logs:


03-11 14:12:31.582 10699-10699/com.example.android.testing_lib E/#####################: btActions called: flags:flagBtOnOff,flagBtStartStopScan 1
03-11 14:12:32.753 10699-10699/com.example.android.testing_lib E/#####################: DeviceFound: HC-05
                                                                                        
                                                                                        :00:21:13:01:E5:6C:10
03-11 14:12:33.163 10699-10699/com.example.android.testing_lib E/#####################: DeviceFound: Micromax A104:D6:5F:E0:65:82:3B:10
03-11 14:12:33.534 10699-10699/com.example.android.testing_lib E/#####################: DeviceFound: Micromax A104:D6:5F:E0:65:82:3B:10
03-11 14:12:34.074 10699-10699/com.example.android.testing_lib E/#####################: DeviceFound: Micromax A104:D6:5F:E0:65:82:3B:10
03-11 14:12:38.268 10699-10699/com.example.android.testing_lib E/#####################: DeviceFound: Micromax A104:D6:5F:E0:65:82:3B:10
03-11 14:12:38.869 10699-10699/com.example.android.testing_lib E/#####################: DeviceFound: Micromax A104:D6:5F:E0:65:82:3B:10
03-11 14:12:39.279 10699-10699/com.example.android.testing_lib E/#####################: DeviceFound: Micromax A104:D6:5F:E0:65:82:3B:10
03-11 14:12:39.700 10699-10699/com.example.android.testing_lib E/#####################: DeviceFound: Micromax A104:D6:5F:E0:65:82:3B:10
03-11 14:12:40.130 10699-10699/com.example.android.testing_lib E/#####################: DeviceFound: Micromax A104:D6:5F:E0:65:82:3B:10
03-11 14:12:40.290 10699-10699/com.example.android.testing_lib E/#####################: DeviceFound: Micromax A104:D6:5F:E0:65:82:3B:10
03-11 14:12:43.393 10699-10699/com.example.android.testing_lib E/#####################: DeviceFound: Micromax A104:D6:5F:E0:65:82:3B:10
03-11 14:12:43.624 10699-10699/com.example.android.testing_lib E/#####################: DeviceFound: Micromax A104:D6:5F:E0:65:82:3B:10
03-11 14:12:44.144 10699-10699/com.example.android.testing_lib E/#####################: DeviceFound: Micromax A104:D6:5F:E0:65:82:3B:10
03-11 14:12:44.314 10699-10699/com.example.android.testing_lib E/#####################: DeviceFound: Micromax A104:D6:5F:E0:65:82:3B:10
03-11 14:12:47.618 10699-10699/com.example.android.testing_lib E/#####################: onFinish: scan finished

all i have are 2 devices, one is a cellphone and other is an arduino. But it is spawning the logs again and again for the cellphone in the discoverylistener.(i am using a slightly modified version of your library)

function refactor: connectToDevice(...)

The function connectToDevice(...) is not calling bluetoothAdapter.cancelDiscovery(); which according to android's default , is unrecommended.

/*

  • Start the remote device discovery process. The discovery process usually involves an inquiry scan
  • of about 12 seconds, followed by a page scan.....
  • .....
  • .....
  • Device discovery is a heavyweight procedure. New connections to

  • remote Bluetooth devices should not be attempted while discovery is in
  • progress, and existing connections will experience limited bandwidth
  • and high latency. Use {@link #cancelDiscovery()} to cancel an ongoing
  • discovery. Discovery is not managed by the Activity,
  • but is run as a system service, so an application should always call
  • {@link BluetoothAdapter#cancelDiscovery()} even if it
  • did not directly request a discovery, just to be sure.
  • Device discovery ....

  • ....
  • ....
    */
    @RequiresPermission(Manifest.permission.BLUETOOTH_ADMIN)
    public boolean startDiscovery() {
    if (getState() != STATE_ON) return false;
    try {
    mServiceLock.readLock().lock();
    if (mService != null) return mService.startDiscovery();
    } catch (RemoteException e) {
    Log.e(TAG, "", e);
    } finally {
    mServiceLock.readLock().unlock();
    }
    return false;
    }

Therefore , I will recommend the following snippet:

public void connectToDevice(BluetoothDevice device, boolean insecureConnection){
        if(bluetoothAdapter.isDiscovering()){
            bluetoothAdapter.cancelDiscovery();
        }
        new ConnectThread(device, insecureConnection).start();
    }

<PS:I know this will be awkward and public and since i don't know of any other medium of discussions on this site, but can I connect with you on some social media platform like facebook or linkedIn? I am an intermediate android developer looking for guidance and funtalks with more experienced people like you :bowtie: 😅 >

NullPointerException when starting another activity

Omar, if I'm not connected to my bluetooth device and I launch another activity, I get the following error:

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.ninecmed.tablet, PID: 5011
    java.lang.RuntimeException: Unable to stop activity {com.ninecmed.tablet/com.ninecmed.tablet.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.bluetooth.BluetoothSocket me.aflak.bluetooth.Bluetooth$ReceiveThread.getSocket()' on a null object reference
        at android.app.ActivityThread.performStopActivityInner(ActivityThread.java:3360)
        at android.app.ActivityThread.handleStopActivity(ActivityThread.java:3406)
        at android.app.ActivityThread.access$1100(ActivityThread.java:147)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1310)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:135)
        at android.app.ActivityThread.main(ActivityThread.java:5253)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.bluetooth.BluetoothSocket me.aflak.bluetooth.Bluetooth$ReceiveThread.getSocket()' on a null object reference
        at me.aflak.bluetooth.Bluetooth.disconnect(Bluetooth.java:297)
        at com.ninecmed.tablet.MainActivity.onStop(MainActivity.java:142)
        at android.app.Instrumentation.callActivityOnStop(Instrumentation.java:1261)
        at android.app.Activity.performStop(Activity.java:6085)
        at android.app.ActivityThread.performStopActivityInner(ActivityThread.java:3357)

Am I doing something incorrect?
Cheers!

unable to use inside broadcast receiver

In my application inside broadcast adapter inside bluetooth on event, I am getting pair devices List and then checking every Device's name separately if any device contain specific sub String then try to connect with that using this library
code of Broadcast:

public class BrodcastBlueTooth extends BroadcastReceiver {

    public BrodcastBlueTooth() {

    }

    @Override
    public void onReceive(Context context, Intent intent) {
        Bluetooth bluetooth;
        bluetooth = new Bluetooth(context);
        String DeviceName=null;
        String action = intent.getAction();
//        Log.d("BroadcastActions", "Action "+action+"received");
        int state;
        BluetoothDevice bluetoothDevice;
        ArrayList<String> pairedDevice;
        pairedDevice=new ArrayList<>();
        final BluetoothAdapter mBtAdapter = BluetoothAdapter.getDefaultAdapter();
        Set<BluetoothDevice> pairedDevices = mBtAdapter.getBondedDevices();

        switch(action)
        {
            case BluetoothAdapter.ACTION_STATE_CHANGED:
                state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, -1);
                if (state == BluetoothAdapter.STATE_OFF)
                {
//                    Toast.makeText(context, "Bluetooth is off", Toast.LENGTH_SHORT).show();
                    Log.d("BroadcastActions", "Bluetooth is off");
                }
                else if (state == BluetoothAdapter.STATE_TURNING_OFF)
                {
//                    Toast.makeText(context, "Bluetooth is turning off", Toast.LENGTH_SHORT).show();
                    Log.d("BroadcastActions", "Bluetooth is turning off");
                }
                else if(state == BluetoothAdapter.STATE_ON)
                {
                    Toast.makeText(context, "Bluetooth is On", Toast.LENGTH_SHORT).show();

                    if (pairedDevices.size() > 0) {
                        for (BluetoothDevice device : pairedDevices) {
                            pairedDevice.add(device.getName());
                        }
                        for(int i=0;i<pairedDevice.size();i++){
                            String name = pairedDevice.get(i);
                            if (name.contains("OBD")){
                            bluetooth.connectToName(name);
                            }else if (name.contains("obd")){
                                String Tname=name;
                                Log.d("Tname", Tname);
                                bluetooth.connectToName(name);
                            }else{
                                Toast.makeText(context,"No device which has obd name",Toast.LENGTH_SHORT).show();
                            }
                        }
                    }
                    Log.d("DevicePaired", String.valueOf(pairedDevice));

                }
                break;


        }

    }
}

Log:


2019-03-17 11:09:17.969 22377-22377/com.example.bluetoothlibraryexample E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.bluetoothlibraryexample, PID: 22377
    java.lang.RuntimeException: Unable to start receiver com.example.bluetoothlibraryexample.BrodcastBlueTooth: android.content.ReceiverCallNotAllowedException: BroadcastReceiver components are not allowed to register to receive intents
        at android.app.ActivityThread.handleReceiver(ActivityThread.java:3047)
        at android.app.ActivityThread.-wrap18(ActivityThread.java)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1561)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6126)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
     Caused by: android.content.ReceiverCallNotAllowedException: BroadcastReceiver components are not allowed to register to receive intents
        at android.app.ReceiverRestrictedContext.registerReceiver(ContextImpl.java:104)
        at android.app.ReceiverRestrictedContext.registerReceiver(ContextImpl.java:93)
        at me.aflak.bluetooth.Bluetooth.onStart(Bluetooth.java:66)
        at com.example.bluetoothlibraryexample.BrodcastBlueTooth.onReceive(BrodcastBlueTooth.java:50)
        at android.app.ActivityThread.handleReceiver(ActivityThread.java:3040)
        at android.app.ActivityThread.-wrap18(ActivityThread.java) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1561) 
        at android.os.Handler.dispatchMessage(Handler.java:102) 
        at android.os.Looper.loop(Looper.java:154) 
        at android.app.ActivityThread.main(ActivityThread.java:6126) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776) 

Using same piece of code inside activity is working fine

Kotlin: No device is being discovered, onDeviceFound never invoked

I am using the library and I'm implementing it using Kotlin, everything is fine when I do scan, stop scan, I have an instance of the Bluetooth class however, I never get to discover new devices and pair to any device

I created a very simple activity, the code is below, I only Toast when a callback is invoked

class MainActivity : AppCompatActivity(), DiscoveryCallback, BluetoothCallback, DeviceCallback {

    private lateinit var bluetooth: Bluetooth
    private var devices: MutableList<BluetoothDevice> = ArrayList()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        setSupportActionBar(toolbar)

        bluetooth = Bluetooth(this)
        bluetooth.onStart()
        bluetooth.setCallbackOnUI(this)
        bluetooth.setDiscoveryCallback(this)
        bluetooth.setBluetoothCallback(this)

        devices.addAll(BluetoothAdapter.getDefaultAdapter().bondedDevices)

        fab.setOnClickListener { view ->
            // to scan uncomment this code
             bluetooth.startScanning()
            // when scanning onDeviceFound callback should be invoked, but for some reasons, it doesn't work when it is being used in Kotlin

            // to pair to the connected device, I was only paired to once device so please change it  accordingly.
//            bluetooth.pair(devices[0])
        }
    }

    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        menuInflater.inflate(R.menu.menu_main, menu)
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        return when (item.itemId) {
            R.id.action_settings -> true
            else -> super.onOptionsItemSelected(item)
        }
    }

    override fun onDevicePaired(device: BluetoothDevice?) {
        Toast.makeText(this, "onDevicePaired", Toast.LENGTH_SHORT).show()
    }

    override fun onDiscoveryStarted() {
        Toast.makeText(this, "onDiscoveryStarted", Toast.LENGTH_SHORT).show()
    }

    override fun onDeviceUnpaired(device: BluetoothDevice?) {
        Toast.makeText(this, "onDeviceUnpaired", Toast.LENGTH_SHORT).show()
    }

    override fun onError(message: String?) {
        Toast.makeText(this, "onError", Toast.LENGTH_SHORT).show()
        Log.d("OnError", message)
    }

    override fun onDiscoveryFinished() {
        Toast.makeText(this, "onDiscoveryFinished", Toast.LENGTH_SHORT).show()
    }

    override fun onDeviceFound(device: BluetoothDevice?) {
        Toast.makeText(this, "onDeviceFound ${device!!.name}", Toast.LENGTH_SHORT).show()
    }

    override fun onUserDeniedActivation() {
        Toast.makeText(this, "onUserDeniedActivation", Toast.LENGTH_SHORT).show()
    }

    override fun onBluetoothOff() {
        Toast.makeText(this, "onBluetoothOff", Toast.LENGTH_SHORT).show()
    }

    override fun onBluetoothOn() {
        Toast.makeText(this, "onBluetoothOn", Toast.LENGTH_SHORT).show()
    }

    override fun onBluetoothTurningOn() {
        Toast.makeText(this, "onBluetoothTurningOn", Toast.LENGTH_SHORT).show()
    }

    override fun onBluetoothTurningOff() {
        Toast.makeText(this, "onBluetoothTurningOff", Toast.LENGTH_SHORT).show()
    }

    override fun onDeviceDisconnected(device: BluetoothDevice?, message: String?) {
        Toast.makeText(this, "onDeviceDisconnected", Toast.LENGTH_SHORT).show()
    }

    override fun onDeviceConnected(device: BluetoothDevice?) {
        Toast.makeText(this, "onDeviceConnected ${device!!.name}", Toast.LENGTH_SHORT).show()
    }

    override fun onConnectError(device: BluetoothDevice?, message: String?) {
        Toast.makeText(this, "onConnectError", Toast.LENGTH_SHORT).show()
    }

    override fun onMessage(message: String?) {
        Toast.makeText(this, "onMessage", Toast.LENGTH_SHORT).show()
    }
}

bluetooth.startScanning
or

bluetooth.pair()

should trigger the invocation off the onDeviceConnected or onDeviceFound

note: when I do scanning, onDiscoveryStarted and onDiscoveryFinished are being invoked

Is anything wrong in this one?

Thank you!

Attempt to invoke virtual method 'java.io.OutputStream me.aflak.bluetooth.Bluetooth$ReceiveThread.getOutputStream()' on a null object reference

Hi, I'm trying to send a message inmediately after the device is connected, but keeps throwing this error:

java.lang.NullPointerException: Attempt to invoke virtual method 'java.io.OutputStream me.aflak.bluetooth.Bluetooth$ReceiveThread.getOutputStream()' on a null object reference

I'm sending it on DeviceCallback using onDeviceConnected function

override fun onDeviceConnected(device: BluetoothDevice) {
statusMessage?.text = getString(R.string.connected)
bluetooth?.send("3")
}

I need to sent the value inmediately after connection to start to read sensors from an arduino

Multiple Bluetooth Client Connections

I would love to see a way to connect and disconnect your client to multiple Bluetooth devices (For example an Android smartphone using this library to connect to multiple HC-06 Bluetooth modules)

As far as I can tell, it will run multiple connections but disconnecting the multiple connections is impossible because the reference to the thread running the receiver is lost when the second connection is made.

Great library though! Keep up the great work!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.