Giter Site home page Giter Site logo

akexorcist / bluetoothspplibrary Goto Github PK

View Code? Open in Web Editor NEW
1.7K 107.0 576.0 4.37 MB

[UNMAINTAINED][Android] Bluetooth Serial Port Profile which comfortable to developer application to communication with microcontroller via bluetooth

License: Apache License 2.0

Java 100.00%

bluetoothspplibrary's Introduction

⚠ WARNING: This project is no longer being maintained

Build Status Android-BluetoothSPPLibrary

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.

Feature

• It's very easy to use

• 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

Download

Maven

<dependency>
  <groupId>com.akexorcist</groupId>
  <artifactId>bluetoothspp</artifactId>
  <version>1.0.0</version>
</dependency>

Gradle

compile 'com.akexorcist:bluetoothspp:1.0.0'

Simple Usage

• Import this library to your workspace and include in to your android project For Eclipse ADT : Download this library and import into your workspace and include this library to your project For Android Studio : Use Gradle to download this library from Maven

• 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

• Stop service with

bt.stopService();

• 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. boolean parameter is mean that data will send with ending by LF and CR or not. If yes your data will added by LF & CR

bt.send("Message", true);

or

bt.send(new byte[] { 0x30, 0x38, ....}, false);

• 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
    }
});

• Using auto 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"

Example

<?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

What's next?

  • Connection Dialog
  • Add Insecure Connection
  • Fix bug on this issue #21
  • Merge the code from #14 for a problem of auto connection
  • Human Readable Log #19

License

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

http://www.apache.org/licenses/LICENSE-2.0

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.

bluetoothspplibrary's People

Contributors

akexorcist 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  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

bluetoothspplibrary's Issues

Failure delivering result onActivityResult

Hi,

I got an Error and App Crash as following:

`public class BluetoothSPPActivity extends AppCompatActivity {

private BluetoothSPP bt;
public static int REQUEST_BLUETOOTH = 1;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_bluetooth_spp);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

// FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
// fab.setOnClickListener(new View.OnClickListener() {
// @OverRide
// public void onClick(View view) {
// Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
// .setAction("Action", null).show();
// }
// });

    bt = new BluetoothSPP(getApplicationContext());
    final TextView receiveSerial = (TextView) findViewById(R.id.recevie_serial);

    bt.setOnDataReceivedListener(new BluetoothSPP.OnDataReceivedListener() {
        public void onDataReceived(byte[] data, String message) {
            receiveSerial.setText("");
            receiveSerial.append(message);
        }
    });

    bt.setBluetoothConnectionListener(new BluetoothSPP.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
        }
    });

    bt.setBluetoothStateListener(new BluetoothSPP.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
            }
        }
    });

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

@Override
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_OTHER);
        } else {
            // Do something if user doesn't choose any device (Pressed back)
        }
    }
}

public void onStart() {
    super.onStart();
    if (!bt.isBluetoothEnabled()) {
        Intent enableBT = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(enableBT, REQUEST_BLUETOOTH);
    } else {
        // bt.startService(BluetoothState.DEVICE_OTHER);
    }
}

}`

Caused by: java.lang.NullPointerException
at app.akexorcist.bluetotohspp.library.BluetoothSPP.connect(BluetoothSPP.java:230)
at com._._*.BluetoothSPPActivity.onActivityResult(BluetoothSPPActivity.java:83)
at android.app.Activity.dispatchActivityResult(Activity.java:5385)

Thanks

Library not working from outside UI

Hi,

I came across a limitation of this library when I tried to connect to a BT device from within a Service (or any sort of Android artifact that does not run under the main thread).

The problem is that the AndroidService class (its treads) can't communicate with the AndroidSPP class via the Handler. Messages are simply lost, and I have most proof that's because they run in a different threads (or should I say, different Loopers). Here is the proof:

If you change in BluetoothSPP.java the line:
private final Handler mHandler = new Handler() {
by
private final Handler mHandler = new Handler(Looper.getMainLooper()) {

Then the library works if you use it from within a Service (or a BroadcastReceiver, I tried both).

I have some concerns about this solution, though: what if I wanted to have two instances of the library running at the same time (and connecting to different BT devices)? Then one's messages would be arriving to the other instance and the other way around... and that's bad. How about creating its own Looper (I don't know how to do that)? Or maybe creating a unique ID per instance and passing it from the SPP to the Service class, and filter the messages based on that ID? It's a bit messy, but it might work.

Please let me know what you think (if you are still alive, of course). I would be very happy to submit a PR if you are happy to accept it.

Weird disconnect() behavior

Dear @akexorcist ,

I am trying to get my app working smoothly with connect() and autoConnect(), and came across a point where isServiceRunning=false and I did not really understand why. Then I looked into your code and I saw:

public void disconnect() {
    if(mChatService != null) {
        isServiceRunning = false;
        mChatService.stop();
        if(mChatService.getState() == BluetoothState.STATE_NONE) {
            isServiceRunning = true;
            mChatService.start(BluetoothSPP.this.isAndroid);
        }
    }
}

May I ask... what's the reason why you stop the service after doing a disconnect()? I really can't get it. If you want to go from a normal connect() to autoConnect() you have to disconnect first... but that kills the service! Does it mean that every time you want to connect() you have to set up the service again?

Thanks!

Suspecting Memory Leak

I used this lib in my project for long time data transmitting.
After the app keeps running 30 minutes, sometimes it will ANR and FC.
So, if anybody got the same problem as mine, comment here please.
I'm suspecting this lib has some memory leak, hoping to get some help.

Maven Repository

Hi,

thank you for your library!!
Do you have a maven repository to use with gradle ?

Thanks you

Anthony

fragment

Is there any possibility to display the devices dialog inside a fragment instead of as intended action?

A core logic error in receive data

public void run() {
    byte[] buffer;
    ArrayList<Integer> arr_byte = new ArrayList<Integer>();

    // Keep listening to the InputStream while connected
    while (true) {
        try {
            int data = mmInStream.read();
            if(data == 0x0A) { 
            } else if(data == 0x0D) {
                buffer = new byte[arr_byte.size()];
                for(int i = 0 ; i < arr_byte.size() ; i++) {
                    buffer[i] = arr_byte.get(i).byteValue();
                }
                // Send the obtained bytes to the UI Activity
                mHandler.obtainMessage(BluetoothState.MESSAGE_READ
                        , buffer.length, -1, buffer).sendToTarget();
                arr_byte = new ArrayList<Integer>();
            } else {
                arr_byte.add(data);
            }
        } catch (IOException e) {
            connectionLost();
            // Start the service over to restart listening mode
            BluetoothService.this.start(BluetoothService.this.isAndroid);
            break;
        }
    }
}

data: 0A 0D 01 02 0A 03 0D
expected: 01 02 0A 03 0D
actual: 01 02 03

Use of the Terminal activity

Hi,

I see that there is a Terminal Activity in this library (not documented), and I would like to use it from my android app if possible.

Is it usable? Could you please provide some brief instructions on how to use it?

Thanks!

Data received error

App crashes when I launch this function, why?

bt.setOnDataReceivedListener(new OnDataReceivedListener() {
public void onDataReceived(byte[] data, String message) {
//Toast.makeText(MainActivity.this, message, Toast.LENGTH_SHORT).show();
byte[] readBuf = (byte[]) data;
int valore_a_16 = ((readBuf[1] & 0xFF) << 8) | (readBuf[0] & 0xFF);
int valore_a_16_2 = ((readBuf[3] & 0xFF) << 8) | (readBuf[2] & 0xFF);
int valore_a_16_3 = ((readBuf[5] & 0xFF) << 8) | (readBuf[4] & 0xFF);
int valore_a_16_4 = ((readBuf[7] & 0xFF) << 8) | (readBuf[6] & 0xFF);
a++;
String str = String.valueOf(valore_a_16);

        Log.d("byte", message);
        text.setText(message);
  }

});

Read byte

hello, I wanted to know if with this library you can read 1024 bytes per second? I have to change something in the code to achieve this speed? thank you!

Either package name or Readme needs fixes

Readme asks to declare activity:

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

in fact that turns out to be with little typo

app.akexorcist.bluetotohspp.library.DeviceList

Possible bug in the autoConnect method

I think I may have found a bug in your autoConnect method, in BluetoothSPP.java:

This is at the bottom of the method where you call the onNewConnection listener

        setBluetoothConnectionListener(bcl);
        c = 0;
        if(mAutoConnectionListener != null)

======> mAutoConnectionListener.onNewConnection(arr_name[c], arr_address[c]);
should be
======> mAutoConnectionListener.onNewConnection(arr_filter_name[c], arr_filter_address[c]);
======> because you connect with arr_filter_address
if(arr_filter_address.size() > 0)
connect(arr_filter_address.get(c));
else
Toast.makeText(mContext, "Device name mismatch", Toast.LENGTH_SHORT).show();

Dave W.

AcceptThread crash

AcceptThread will crash if listenUsingRfcommWithServiceRecord method throws exception.
In this case mmServerSocket will be null,
and crash will be at AcceptThread.run line socket = mmServerSocket.accept();

Also need to check for null in AcceptThread .cancel method or catch any exception.

Possible crash (out of bounds) in BluetoothSPP.autoConnect, wrong address & name passed to callback

            String[] arr_name = getPairedDeviceName();
            String[] arr_address = getPairedDeviceAddress();
            for(int i = 0 ; i < arr_name.length ; i++) {
                if(arr_name[i].contains(keywordName)) {
                    arr_filter_address.add(arr_address[i]);
                    arr_filter_name.add(arr_name[i]);
                }
            }
...
...
...
            c = 0;
            if(mAutoConnectionListener != null)
                mAutoConnectionListener.onNewConnection(arr_name[c], arr_address[c]); <-- crash

if device don't have paired devices

Also the wrong name and address are passed to onNewConnection callback,
because the library will try to connect to filtered device which can have a different array index.

if(arr_filter_address.size() > 0) 
                connect(arr_filter_address.get(c));
            else 
                Toast.makeText(mContext, "Device name mismatch", Toast.LENGTH_SHORT).show();

Or the library will not even try to connect if there is no devices which match the filter.

nullpointer exception

Hello,
Is there a working example anywhere except for the few lines in the readme file?
Where does this line come from?
setup();
when following the github instructions i get a nullpointer exception when trying to connect to a device. I would appreciate any help :)
Regards,
Lukas

java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=384, result=-1, data=Intent { (has extras) }} to activity {com.example.lukas.bluetoothgraph/com.example.lukas.bluetoothgraph.MainInterface}: java.lang.NullPointerException
            at android.app.ActivityThread.deliverResults(ActivityThread.java:3592)
            at android.app.ActivityThread.handleSendResult(ActivityThread.java:3635)
            at android.app.ActivityThread.access$1300(ActivityThread.java:155)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1379)
            at android.os.Handler.dispatchMessage(Handler.java:110)
            at android.os.Looper.loop(Looper.java:193)
            at android.app.ActivityThread.main(ActivityThread.java:5407)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:855)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:671)
            at dalvik.system.NativeStart.main(Native Method)
     Caused by: java.lang.NullPointerException
            at app.akexorcist.bluetotohspp.library.BluetoothSPP.connect(BluetoothSPP.java:230)
            at com.example.lukas.bluetoothgraph.MainInterface.onActivityResult(MainInterface.java:38)
            at android.app.Activity.dispatchActivityResult(Activity.java:5469)
            at android.app.ActivityThread.deliverResults(ActivityThread.java:3588)
            at android.app.ActivityThread.handleSendResult(ActivityThread.java:3635)
            at android.app.ActivityThread.access$1300(ActivityThread.java:155)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1379)
            at android.os.Handler.dispatchMessage(Handler.java:110)
            at android.os.Looper.loop(Looper.java:193)
            at android.app.ActivityThread.main(ActivityThread.java:5407)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:855)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:671)
            at dalvik.system.NativeStart.main(Native Method)

What if data recieved contains 0d or 0a ?

The data we receive can randomly contain byte 0d or 0a. This won't be passed down the line through onDataReceived in BluetoothSPP.OnDataReceivedListener(). and the app won't receive correct data.

There should be a way to pass down all raw data to the listener.

This is the code from BluetoothService.java line 358

int data = mmInStream.read();
if(data == 0x0A) { 
} else if(data == 0x0D) {
    buffer = new byte[arr_byte.size()];
    for(int i = 0 ; i < arr_byte.size() ; i++) {
        buffer[i] = arr_byte.get(i).byteValue();
    }
    // Send the obtained bytes to the UI Activity
    mHandler.obtainMessage(BluetoothState.MESSAGE_READ
        , buffer.length, -1, buffer).sendToTarget();
    arr_byte = new ArrayList<Integer>();
} else {
    arr_byte.add(data);
}

PIN

Hi,
thanks for this useful lib,
is there anyway to enter pin for connecting automatically?

Listener for bluetooth connection status

when i use
bt.setBluetoothConnectionListener(new BluetoothConnectionListener() {
it says cannot resolve symbol setBluetoothConnectionListener and invalid method declaration for BluetoothConnectionListener()

What am I doing wrong? Can anyone help me?

Connect with address

What are the reason for connect directly dont work with the device?
i Try with
bt = new BluetoothSPP(this);
bt.setupService() ;
bt.startService(BluetoothState.DEVICE_OTHER);
bt.connect("F4:B8:5E:8C:BB:11");

Note: the device is not paried and already define ReceivedListener , ConnectionListener

Handler not working outside an Activity

Hi,

I have a problem with your library and I'm a bit lost. If I use it from an Activity (UI) it works fine but, if I use it from a BroadcastReceiver (connect to a BT device on the background from outside the app) then the library does not work well.

I have been inserting debug messages inside the library and my conclusion is that the mHandler from BluetoothSPP does not receive the messages sent from BluetoothService. The message is simply lost!

Any idea why could this be happening?

Thanks!

Device Only Discoverable When Bluetooth Setting Open?

Hi,
I'm using your library to simplify sending control data from a Glass to another Android device. It's working well once the connection is established, but the Glass doesn't seem to find the other device until I open the Bluetooth settings on that device. I've tried pairing the Glass with my phone instead of the device I'm working on, and it sees that immediately. I'm using a custom device selection list rather than your built-in since it needs to work in the Glass UI. Do you have any idea why the other device would only be discoverable after opening its Bluetooth settings?
Thanks!
Jeremy

Device list documentation not up to date

Hi,

Thanks your great lib !

I think there is a mistake in the documentation which should be :
<activity android:name="app.akexorcist.bluetotohspp.library.DeviceList" />

Autoconnect to multiple devices

First of all, thanks a lot for your library! This is exactly what I needed.

I am wondering... would you be willing to accept pull requests to modify the autoConnect method to allow a list of BT names as parameters (full match) besides a keyword (partial match)?
You see, I already have the list of BT devices that I want to autoconnect to, and don't necesarily match a common keyword.

It's actually a very small change, but if you are not willing to accept PRs then I won't even bother.

Alternatively, one could still use keywords but add $ and ^ to the end/begin. What I would still be missing is accept a list of keywords instead of a string.
Thanks!

Permission issues

If I import this library with Gradle, I get permissions that access external storage and device identity??
But when I import this manually myself I don't get those. What's happening?

Device list Activity

Hey, i am new to Android Programming.
I am encountering a problem, The android Studio reporting an error it says that it cant find the DeviceList.class.
In the Android Manifest File.xml, When I declare the library activity it says it cannot resolve the symbol.
I've declared the library and activity and every other feature works fine. Can u help me?
A Sample program using the commands will help me immensely, if u have it.
Thanks for this Library.

How to use this Library between two diffrent Activitys?

I got three Activitys.

"MainActivity" is for init SDK.
"DeviceListActivity" is for finding bluetooth-device.
"DataSendActivity" is for sending data and show data recived.

And, my problem is "DataSendActivity" is not able to use.

I have look into Library's sample, but there is no solution.

Please help me.

Real Android Service

Hi,
in my opinion it would be useful to have a real Android Service Handling the Connection, since a simple change of orientation (when used in Fragment), leads to loosing the connection. I think it would be more stable, if the BluetoothSPP object could be independent from the context, or at least a way to change the context and handling if there currently is no displayed activity.
Greets Nico

Device List Activity

Hey, i am new to Android Programming.
I am encountering a problem. After I use the Intent to choose device activity and when I check result data on onActivityResult, i get an error at bt.connect(data), can you pls explain what does bt.connect does? Is it used to to connect to the device? Does the variable ' data' contain the Mac address?
I've declared the library and activity and every other feature works fine. Can u help me?
A Sample program using the commands will help me immensely, if u have it.
Thanks for this Library.

Error in Resource File .

Type error: Error retrieving parent for item: No resource found that matches the given name 'android:Theme.Material.Light'. styles.xml /Main/res/values-v21 line 3 Android AAPT Problem

OnDataReceived

hi,

I have tried this code and everything is working fine except data receive , i am not able to receive data by my HC-05 module .

Data send by mobile is working fine , please suggest

no data incoming

bt connect is ok.

in terminal mode, "send" is OK

I can send data to pc.

public void setup() {
    Button btnSend = (Button)findViewById(R.id.btnSend);
    btnSend.setOnClickListener(new OnClickListener(){
        public void onClick(View v){
            if(etMessage.getText().length() != 0) {
                bt.send(etMessage.getText().toString(), true);
                textRead.append("hello " + "\n");//-----------------------------  for Check
                etMessage.setText("");
            }
        }
    });
}

but i cant receive data from pc

bt.setOnDataReceivedListener(new OnDataReceivedListener() {
public void onDataReceived(byte[] data, String message) {
// Do something when data incoming
textRead.append(message + "\n");
}

});

Multiple other device(none android) connection

hi,
i have used your library for my Bluetooth connection between my android phone and one other device,but my project would be complete if i can connect to multiple other device.i try to connect to multiple device with multiple object created from BluetoothSPP class , but when i connect another device my last connection broke and new connection with new device replaced....how can i hold both connection ?

Android bluetooth device not working

I cant connect to bluetooth device like my Nokia cell phone and like a Android Bluetooth phone. Theres anything that I doing wrong? What are bluetooth serial port profile devices supported?

Improvement Suggested

Maybe BluetoothState Class elements should be in Enum form. As then the Logcat outputs like 'setState() 1 -> 2' could be printed easily as 'setState() STATE_LISTEN -> STATE_CONNECTING' which I think might be more human readable strings.
What does the author of the Repo think? Is this a better approach?

Newline inconsistencies

I've been trying to get both the receiver and transmitter to work properly but one of the sides always behaved strange. Correct me if I'm wrong, but after looking at the code it seems like CRLF is sent in different order depending on which method you use:

In BluetoothSPP.java:269:

public void send(byte[] data, boolean CRLF) {
   ...
   data2[data2.length - 2] = 0x0A; 
   data2[data2.length - 1] = 0x0D; 
   ...

So in this case, when writing raw data, the data transmitted is <payload><0x0A><0x0D>. However, when checking the other send method:

public void send(String data, boolean CRLF) {
   ...
   if(CRLF)  
      data += "\r\n";  
   ...

If I do a quick check for this in Python:

>>> hex(ord('\r'))
'0xd'
>>> hex(ord('\n'))
'0xa'

In this case the transmitted data will actually be <payload><0x0D><0x0A>. Or am I missing something?

Fuse Android-BluetoothSPPLibrary with other android project

I tried to fuse Android-BluetoothSPPLibrary with my android project. I am using Android Studio and i import library module into my project. Then I modified Terminal Activity as my Main Activity. Everything go well except I cant connect any devices. When i use the original project, everything is fine. Any suggestion?

Getting Build Error with ver 1.0.1 of Android Studio,

I am getting the following error when I try to build the library with Android Studio 1.0.1:

Executing tasks: [:app:compileDebugSources, :library:compileDebugSources]

Configuration on demand is an incubating feature.

FAILURE: Build failed with an exception.

  • What went wrong:
    A problem occurred configuring root project 'Android-BluetoothSPPLibrary-master'.

    java.lang.NullPointerException (no error message)

  • Try:
    Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

BUILD FAILED

Total time: 0.685 secs

I have tried many things to try and get rid of this error, but have had no luck in doing so. Any help would be greatly appreciated.

Thanks in advance,

Dave Walters

Not able to receive

Hi,

I am sure I am making something wrong... so this is more a question than an "issue". Anyway, here it goes.

I have an activity with (some code stripped):

public class ViewDeviceActivity extends Activity {
    BluetoothSPP bt;

    protected void onCreate(Bundle savedInstanceState) {
        bt = new BluetoothSPP(this);
    }

    public void onStart() {
        bt.setBluetoothConnectionListener(new BluetoothSPP.BluetoothConnectionListener() {
            public void onDeviceConnected(String name, String address) {
                Log.i("Sensorino", "Connected, sending data...");
                bt.send("blah",false);
            }
        });
        bt.setOnDataReceivedListener(new BluetoothSPP.OnDataReceivedListener() {
            public void onDataReceived(byte[] data, String message) {
                // Do something when data incoming
                Log.i("Sensorino", "Received bytes: "+data.length);
            }
        });
        bt.setupService();
        bt.startService(BluetoothState.DEVICE_OTHER);

        Log.i("Sensorino", "Connecting to " + device.getRemote_address());
        bt.connect(device.getRemote_address());
    }
}

The problem is that I am able to send (on the other end I see "blah") but not able to receive. I have tried with both the sample BluetoothChat from googlecode and from my HC-05 device: same with both.

The thing that drives me mad is that I ACTUALLY see the data getting into the device (I enabled Bluetooth Debugging and see the packet with the data in the /sdcard) but the data does not reach my activity.

Is there anything I am doing wrong?

The only strange thing I see in the logcat is:
W/BluetoothAdapter﹕ getBluetoothService() called with no BluetoothManagerCallback

It would actually help if you tell me what's the minimum methods and the right order to call them in order to have I/O working. If I understand correctly (I am not an Android expert) I am doing the following:

bt = new BluetoothSPP(this);
bt.setBluetoothConnectionListener(new xxx);
bt.setOnDataReceivedListener(new xxx);
bt.setupService();
bt.startService(BluetoothState.DEVICE_OTHER);
bt.connect(device.getRemote_address());
bt.send("blah",false);

I tried shuffling the setupService and startService up and down with the same result.

Thanks!

How does Autoconnect work?

Hi,
I am not sure if this is the right place to write this question.
But I wanted to know how does Autocorrect work? Does it keep on polling for the device of interest after a particular interval?

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.