Giter Site home page Giter Site logo

developerpaul123 / simplebluetoothlibrary Goto Github PK

View Code? Open in Web Editor NEW
137.0 13.0 34.0 364 KB

Android library for simplifying bluetooth usage.

License: Apache License 2.0

Java 78.61% HTML 13.00% JavaScript 0.04% CSS 8.35%
android bluetooth java android-library android-libs android-lib android-libraries android-bluetooth android-bluetooth-device simple

simplebluetoothlibrary's Introduction

SimpleBluetoothLibrary

Android Arsenal

Description

This library makes it easy for you to implement bluetooth in your Android app. The SimpleBlueooth class handles all the hard work for you and all you have to do is make a few method calls.

Dependency

repositories {
    ....
    maven {url "https://jitpack.io"}
}
dependencies {
    ....
    compile  'com.github.DeveloperPaul123:SimpleBluetoothLibrary:1.5.1'
}

Requirements

Min SDK Level is 14 or Android IceCreamSandwich

Usage

This library provides a BaseBluetoothActivity that you inherit from to easily take care of:

  • Enabling bluetooth
  • Scanning for new devices.
  • Connecting to a device.
  • Receiving data from the device.
  • Sending data to the device.

As an example:

public class TestActivity extends BaseBluetoothActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //set your content view here. 
    }

    @Override
    public void onBluetoothEnabled() {
        super.onBluetoothEnabled();
        //this is always called, when bluetooth is enabled.
        //by default the activity will start a scan. If you don't want this
        //delete the super call. 
    }

    @Override
    public void onDeviceSelected(String macAddress) {
        super.onDeviceSelected(macAddress);
        //this is called when a device is selected from the scan activity. By default,
        //the selected device will be connected to. If you don't want this, delete the super call.
    }

    @Override
    public void onBluetoothDataReceived(byte[] bytes, String data) {
       //called when data is received from the device. 
    }

    @Override
    public void onDeviceConnected(BluetoothDevice device) {

    }

    @Override
    public void onDeviceDisconnected(BluetoothDevice device) {

    }

    @Override
    public void onDiscoveryStarted() {

    }

    @Override
    public void onDiscoveryFinished() {

    }
}

Alternatively you can use the SimpleBluetooth class yourself:

public class MainActivity extends Activity {

    private SimpleBluetooth simpleBluetooth;
    private static final int SCAN_REQUEST = 119;
    private static final int CHOOSE_SERVER_REQUEST = 120;
    //...other code....//
    private String curMacAddress;

    @Override
    protected void onResume() {
        super.onResume();
        simpleBluetooth = new SimpleBluetooth(this, new SimpleBluetoothListener() {

            @Override
            public void onBluetoothDataReceived(byte[] bytes, String data) {
                //read the data coming in.
            }

            @Override
            public void onDeviceConnected(BluetoothDevice device) {
                //a device is connected so you can now send stuff to it
                
            }

            @Override
            public void onDeviceDisconnected(BluetoothDevice device) {
                // device was disconnected so connect it again?
               
            }

            @Override
            public void onDiscoveryStarted() {

            }

            @Override
            public void onDiscoveryFinished() {

            }
        });
        simpleBluetooth.initializeSimpleBluetooth();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //...other code...//
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        } else if (id == R.id.scan) {
            simpleBluetooth.scan(SCAN_REQUEST);
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == SCAN_REQUEST || requestCode == CHOOSE_SERVER_REQUEST) {

            if(resultCode == RESULT_OK) {

                curMacAddress = data.getStringExtra(DeviceDialog.DEVICE_DIALOG_DEVICE_ADDRESS_EXTRA);
                if(requestCode == SCAN_REQUEST) {
                    simpleBluetooth.connectToBluetoothDevice(curMacAddress);
                } else {
                    simpleBluetooth.connectToBluetoothServer(curMacAddress);
                }

            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        simpleBluetooth.endSimpleBluetooth();
    }
}

Finally, the library allows for an alternative way to receive data. Say you're using an Arduino or something similar that is sending out a newline character at the end of every loop. You can read this data using a buffered input type through the following line:

simpleBluetooth.setInputStreamType(BluetoothUtility.InputStreamType.BUFFERED);

This will case the input type to change and you should receieve the data line by line.

Additionally, this library allows for the creation and connection to a bluetooth server. Simply call:

simpleBluetooth.createBluetoothServerConnection();

and on the connecting device call:

//curMacAddress is the address of the server device.
simpleBluetooth.connectToBluetoothServer(curMacAddress);

Finally, the library can handle A2DP protocols, although this has not yet been tested.

Developed By

Paul T

Credit to afollestad for his material-dialog library

License

Copyright 2014 - 2017 Paul T

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.

simplebluetoothlibrary's People

Contributors

developerpaul123 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

simplebluetoothlibrary's Issues

can not receive message

I copy the code from the sample to my project.
But I don't know why I could only receive message once after countless tries to make two android phone communicate with simpleBluetooth.createBluetoothServerConnection() and simpleBluetooth.connectToBluetoothServer(curMacAddress);

the two android phones versions are 4.2.1 and 4.4.4

Initialize with flag to disable toast messages

It would be great if all toast messages could be disabled with a flag when initialized, in certain scenarios we do not want to display messages such as "Device not available." and "Device connected!".

Fatal SIGSEGV 11 Error

Calling simplebluetooth.endSimpleBluetooth() causes a system crash if your bluetooth socket is recieving information while you are closing the socket, resulting in a fatal segmentation error. This is probably due to trying to access the socket input stream after the socket is closed. Should try to synchronize calls to ending all the separate threads and add a flag so that when thread.cancel() is called, the input stream is never accessed (boolean flag or look at isInterrupted()).

BluetoothUtility.closeConnections() crashes

BluetoothUtility.closeConnections() crashes when called with a connected BT device. The call looks like this:
BluetoothUtility bu = simpleBluetooth.getBluetoothUtility();
bu.closeConnections();

Tracing shows calling the close method of the Connected thread causes a problem:
public void cancel() {
try {
this.mmSocket.close();
} catch (IOException var2) {
;
}
}`

device not avaible error

public class MainActivity extends AppCompatActivity {

private SimpleBluetooth simpleBluetooth;
private static final int SCAN_REQUEST = 119;
private static final int CHOOSE_SERVER_REQUEST = 120;
private String curMacAddress;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    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();
        }
    });
}

@Override
protected void onResume() {
    super.onResume();
    simpleBluetooth = new SimpleBluetooth(this, this);
    simpleBluetooth.initializeSimpleBluetooth();
    simpleBluetooth.setSimpleBluetoothListener(new SimpleBluetoothListener() {

        @Override
        public void onBluetoothDataReceived(byte[] bytes, String data) {
            //read the data coming in.

        }

        @Override
        public void onDeviceConnected(BluetoothDevice device) {
            //a device is connected so you can now send stuff to it

        }

        @Override
        public void onDeviceDisconnected(BluetoothDevice device) {
            // device was disconnected so connect it again?

        }

        @Override
        public void onDiscoveryStarted() {
            Log.i("BService","discover started");

        }

        @Override
        public void onDiscoveryFinished() {
            Log.i("BService","discover finished");
        }
    });

}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    if (id == R.id.action_settings) {
        //simpleBluetooth.getBluetoothUtility().enableDiscovery(300);
        simpleBluetooth.makeDiscoverable(300);
        return true;
    } else if (id == R.id.scan) {
        simpleBluetooth.scan(SCAN_REQUEST);
        return true;
    }

    return super.onOptionsItemSelected(item);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if(requestCode == SCAN_REQUEST || requestCode == CHOOSE_SERVER_REQUEST) {

        if(resultCode == RESULT_OK) {

            curMacAddress = data.getStringExtra(DeviceDialog.DEVICE_DIALOG_DEVICE_ADDRESS_EXTRA);
            if(requestCode == SCAN_REQUEST) {
                Log.i("BService","try to connect : " + curMacAddress);
                simpleBluetooth.connectToBluetoothDevice(curMacAddress);
            } else {
                simpleBluetooth.connectToBluetoothServer(curMacAddress);
            }

        }
    }
}

@Override
protected void onDestroy() {
    super.onDestroy();
    simpleBluetooth.endSimpleBluetooth();
}

}

i am trying to make little chat with using your lib. but i always get 'device not avaible' error.
i make both of device discoverable from app then start to scan from one device and try to connect other one but i get this error.

Nexus 5 doesn't scan any devices

On my two Nexus 5 device scanner doesn't work. Devices list on dialog is always empty. Nexus can see other devices only from settings screen, not for my app. Other phones (Samsung Galaxy S3, Huawei, OnePlus3T) scan correctly. Device pairing with Nexus work fine, however I have to do it from settings (due empty list). Could you reproduce this issue?

Create new sendData(byte[] bytes) method

It would be useful to have a method with a bytes[] parameter seeing as you already have a corresponding write(byte[] bytes) method in BluetoothUtility.class.

    public void sendData(byte[] bytes) {
        if(this.bluetoothSocket != null && this.bluetoothSocket.isConnected() && this.connectedThread != null) {
            this.connectedThread.write(number);
        }
    }

Data Lossed with arduino

Hi, this is Dave.
Is there anyway to prevent data loss when connected to an arduino with bluetooth?
I have connected arduino to my galaxy s6 edge.
It works fine with the bluetooth Serial application, but I couldn't figure it out why.

Silent enableBluetooth() method

Currently your enableBluetooth() method will prompt the user if they wish to enable bluetooth, however seeing as the manifest has BLUETOOTH_ADMIN permission it would be useful if there was a way of enabling bluetooth without the prompt. Whilst I agree a dialog is best practice in most scenarios, there are issues in environments such as public kiosks etc where such tasks need to be completed in the background.

It would be good if there was a flag used when calling initializeSimpleBluetooth() to specify if in silent mode or not. Then any resultant calls of bluetoothUtility.enableBluetooth() would check whether to enable with enableBluetooth() or enableBluetoothSilent().

    public void enableBluetooth() {
        if(this.bluetoothAdapter != null && !this.checkIfEnabled()) {
            Intent enableBluetooth = new Intent("android.bluetooth.adapter.action.REQUEST_ENABLE");
            this.mActivity.startActivityForResult(enableBluetooth, 1001);
        }

    }
    public void enableBluetoothSilent() {
        if(this.bluetoothAdapter != null && !this.checkIfEnabled()) {
            bluetoothAdapter.enable()
        }

    }

Update to latest libs

com.android.support:support-v4:24.2.1
com.android.support:appcompat-v7:24.2.1
com.afollestad.material-dialogs:core:0.9.0.2

incomplete data

i seem to be getting incomplete data string when passing a string concatenated with a base64 image. The base64 data is sent partial. e.g String1+":"+"String2+":"+base64image

Data not complete

Hi,
When my device reads the data coming in from the Arduino the data is coming in chopped, the data im receiving comes in very fast.
Log:
03-20 21:35:18.693 30385-30385/com.bluetooth.juandiaz.bluetoothconnectivity D/data:: 1
03-20 21:35:18.699 30385-30385/com.bluetooth.juandiaz.bluetoothconnectivity D/data:: 22in, 313
03-20 21:35:18.805 30385-30385/com.bluetooth.juandiaz.bluetoothconnectivity D/data:: 9
03-20 21:35:18.818 30385-30385/com.bluetooth.juandiaz.bluetoothconnectivity D/data:: 0in, 231c
03-20 21:35:18.917 30385-30385/com.bluetooth.juandiaz.bluetoothconnectivity D/data:: 8
03-20 21:35:18.943 30385-30385/com.bluetooth.juandiaz.bluetoothconnectivity D/data:: 9in, 229cm
03-20 21:35:19.043 30385-30385/com.bluetooth.juandiaz.bluetoothconnectivity D/data:: 8
03-20 21:35:19.044 30385-30385/com.bluetooth.juandiaz.bluetoothconnectivity D/data:: 9in, 228cm
03-20 21:35:19.168 30385-30385/com.bluetooth.juandiaz.bluetoothconnectivity D/data:: 8
03-20 21:35:19.170 30385-30385/com.bluetooth.juandiaz.bluetoothconnectivity D/data:: 9in, 228c
03-20 21:35:19.268 30385-30385/com.bluetooth.juandiaz.bluetoothconnectivity D/data:: 8
03-20 21:35:19.273 30385-30385/com.bluetooth.juandiaz.bluetoothconnectivity D/data:: 9in, 228cm
03-20 21:35:19.394 30385-30385/com.bluetooth.juandiaz.bluetoothconnectivity D/data:: 8
03-20 21:35:19.397 30385-30385/com.bluetooth.juandiaz.bluetoothconnectivity D/data:: 9in, 228cm
03-20 21:35:19.492 30385-30385/com.bluetooth.juandiaz.bluetoothconnectivity D/data:: 8
03-20 21:35:19.518 30385-30385/com.bluetooth.juandiaz.bluetoothconnectivity D/data:: 9in, 228cm

however the data should read:
03-20 21:35:18.693 30385-30385/com.bluetooth.juandiaz.bluetoothconnectivity D/data:: 122in, 313cm
03-20 21:35:18.805 30385-30385/com.bluetooth.juandiaz.bluetoothconnectivity D/data:: 90in, 231cm

do you know what could cause this?

also i tried using
simpleBluetooth.setInputStreamType(BluetoothUtility.InputStreamType.BUFFERED);
and
simpleBluetooth.setInputStreamType(BluetoothUtility.InputStreamType.NORMAL);
but is not working

im using an arduino with a proximity sensor

Thanks for the help

Unable to send to Arduino

I am trying to send data from Android to Arduino. I am able to receive data using the sample MainActivity class in the readme.

The code looks like this :

        @Override
            public void onDeviceConnected(BluetoothDevice device) {
                //a device is connected so you can now send stuff to it
                Log.d("BA", "Connected");
                for (int i = 0; i < 100; i++) {
                    simpleBluetooth.sendData("a"); // sending ack
                    Log.d("BA", "Sent a");
                    Thread.sleep(1000);
                }
            }

Where am I going wrong?

error: Error:Could not find property 'plugin'

Hi I just started to learn android, I use Android Studio.
I got error:

Error:Could not find property 'plugin' on com.android.build.gradle.LibraryExtension_Decorated@176deea7.

How can I fix it? thanks > <

Bluetooth Service

Create a background bluetooth service that can be started within an app and still run when the app is closed.

Issue with Device to Device Communication

hi.
first of all: thankx for sharing this library!!
i cannot start a server...it tries for a long time but nothing happens. my logcat says:

BluetoothAdapter﹕ getBluetoothService() called with no BluetoothManagerCallback

bye
phil

Update support library 23.2.0

Hi, could I ask you to update the library com.github.afollestad.material-dialogs because this library refers to the resource @drawable/abc_ic_ab_back_mtrl_am_alpha and this resource in support library 23.2.0 was renamed to @drawable/abc_ic_ab_back_material. When I tried to update support library I cannot build my app.

Thanks a lot

Receiving partial data from Arduino

Hi Paul,

I'm using your library for one of my project and it's working really good except for one part. I'm trying to send a message from Arduino and when I receive it via your library, I see only half or quarter of the message. I tried using BlueTerm(another bluetooth App) and I received it properly there. So, it's probably an issue on your side. Here is an example :

ORIGINAL MESSAGE (FROM ARDUINO) : 345#233#256#864$

RECEIVED BY YOUR LIBRARY : 345#233 and then 256#864#

RECEIVED BY BLUETERM : 345#233#256#864$ (no issues)

Basically, what's happening is that I'm receiving the first part and then the second part.

Can you look into it? Regards

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.