Trying to use bluetooth, but lack understanding of handler - java

my last question was closed because not focused enough. My goal is to send an array to a Bluetooth module hc-06 to pilot an Arduino. I have made research and visited this page (among many other):Android sample bluetooth code to send a simple string via bluetooth
I would be interested in an explanation to make the following code work:
import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Set;
import java.util.UUID;
public class multiplayerConnect extends AppCompatActivity {
public static final int REQUEST_ENABLE_BT=1;
ListView lv_paired_devices;
Set<BluetoothDevice> set_pairedDevices;
ArrayAdapter adapter_paired_devices;
BluetoothAdapter bluetoothAdapter;
public static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
public static final int MESSAGE_READ=0;
public static final int MESSAGE_WRITE=1;
public static final int CONNECTING=2;
public static final int CONNECTED=3;
public static final int NO_SOCKET_FOUND=4;
String bluetooth_message="00";
#SuppressLint("HandlerLeak")
Handler mHandler=new Handler()
{
#Override
public void handleMessage(Message msg_type) {
super.handleMessage(msg_type);
switch (msg_type.what){
case MESSAGE_READ:
byte[] readbuf=(byte[])msg_type.obj;
String string_recieved=new String(readbuf);
//do some task based on received string
break;
case MESSAGE_WRITE:
if(msg_type.obj!=null){
ConnectedThread connectedThread=new ConnectedThread((BluetoothSocket)msg_type.obj);
connectedThread.write(bluetooth_message.getBytes());
}
break;
case CONNECTED:
Toast.makeText(getApplicationContext(),"Connected",Toast.LENGTH_SHORT).show();
break;
case CONNECTING:
Toast.makeText(getApplicationContext(),"Connecting...",Toast.LENGTH_SHORT).show();
break;
case NO_SOCKET_FOUND:
Toast.makeText(getApplicationContext(),"No socket found",Toast.LENGTH_SHORT).show();
break;
}
}
};
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.multiplayer_bluetooth);
initialize_layout();
initialize_bluetooth();
start_accepting_connection();
initialize_clicks();
}
public void start_accepting_connection()
{
//call this on button click as suited by you
AcceptThread acceptThread = new AcceptThread();
acceptThread.start();
Toast.makeText(getApplicationContext(),"accepting",Toast.LENGTH_SHORT).show();
}
public void initialize_clicks()
{
lv_paired_devices.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
Object[] objects = set_pairedDevices.toArray();
BluetoothDevice device = (BluetoothDevice) objects[position];
ConnectThread connectThread = new ConnectThread(device);
connectThread.start();
Toast.makeText(getApplicationContext(),"device choosen "+device.getName(),Toast.LENGTH_SHORT).show();
}
});
}
public void initialize_layout()
{
lv_paired_devices = (ListView)findViewById(R.id.lv_paired_devices);
adapter_paired_devices = new ArrayAdapter(getApplicationContext(),R.layout.support_simple_spinner_dropdown_item);
lv_paired_devices.setAdapter(adapter_paired_devices);
}
public void initialize_bluetooth()
{
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter == null) {
// Device doesn't support Bluetooth
Toast.makeText(getApplicationContext(),"Your Device doesn't support bluetooth. you can play as Single player",Toast.LENGTH_SHORT).show();
finish();
}
//Add these permisions before
// <uses-permission android:name="android.permission.BLUETOOTH" />
// <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
// <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
// <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
if (!bluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
else {
set_pairedDevices = bluetoothAdapter.getBondedDevices();
if (set_pairedDevices.size() > 0) {
for (BluetoothDevice device : set_pairedDevices) {
String deviceName = device.getName();
String deviceHardwareAddress = device.getAddress(); // MAC address
adapter_paired_devices.add(device.getName() + "\n" + device.getAddress());
}
}
}
}
public class AcceptThread extends Thread
{
private final BluetoothServerSocket serverSocket;
public AcceptThread() {
BluetoothServerSocket tmp = null;
try {
// MY_UUID is the app's UUID string, also used by the client code
tmp = bluetoothAdapter.listenUsingRfcommWithServiceRecord("NAME",MY_UUID);
} catch (IOException e) { }
serverSocket = tmp;
}
public void run() {
BluetoothSocket socket = null;
// Keep listening until exception occurs or a socket is returned
while (true) {
try {
socket = serverSocket.accept();
} catch (IOException e) {
break;
}
// If a connection was accepted
if (socket != null)
{
// Do work to manage the connection (in a separate thread)
mHandler.obtainMessage(CONNECTED).sendToTarget();
}
}
}
}
private class ConnectThread extends Thread {
private final BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;
public ConnectThread(BluetoothDevice device) {
// Use a temporary object that is later assigned to mmSocket,
// because mmSocket is final
BluetoothSocket tmp = null;
mmDevice = device;
// Get a BluetoothSocket to connect with the given BluetoothDevice
try {
// MY_UUID is the app's UUID string, also used by the server code
tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) { }
mmSocket = tmp;
}
public void run() {
// Cancel discovery because it will slow down the connection
bluetoothAdapter.cancelDiscovery();
try {
// Connect the device through the socket. This will block
// until it succeeds or throws an exception
mHandler.obtainMessage(CONNECTING).sendToTarget();
mmSocket.connect();
} catch (IOException connectException) {
// Unable to connect; close the socket and get out
try {
mmSocket.close();
} catch (IOException closeException) { }
return;
}
// Do work to manage the connection (in a separate thread)
// bluetooth_message = "Initial message"
// mHandler.obtainMessage(MESSAGE_WRITE,mmSocket).sendToTarget();
}
/** Will cancel an in-progress connection, and close the socket */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}
}
private class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket) {
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the input and output streams, using temp objects because
// member streams are final
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) { }
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
byte[] buffer = new byte[2]; // buffer store for the stream
int bytes; // bytes returned from read()
// Keep listening to the InputStream until an exception occurs
while (true) {
try {
// Read from the InputStream
bytes = mmInStream.read(buffer);
// Send the obtained bytes to the UI activity
mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer).sendToTarget();
} catch (IOException e) {
break;
}
}
}
/* Call this from the main activity to send data to the remote device */
public void write(byte[] bytes) {
try {
mmOutStream.write(bytes);
} catch (IOException e) { }
}
/* Call this from the main activity to shutdown the connection */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}
}
}
I tried to add a button on my end to use the "write" function. However, as it belongs to the ConnectedThread class, I can't use it directly. So I tried to use the handler, but apparently, the message I made has an obj=null. I read the documentation about the "messages" but I did not manage to resolve the problem. There are no errors until I try to add the obj in which case the code doesn't compile. When i removed the if (message_type.obj != null) my application just stopped.
To summarize: I want to send data via Bluetooth. I made my research, but I need a helping hand to use the handler.

Related

Android: Bluetooth Trouble opening server socket

I am currently in the middle of building an Android app with bluetooth capabilties and am having some issue establishing a server socket. End goal currently is to exchange strings between devices and then pass those back to the main activity. When attempting to open a socket I continually get the error:
W/System.err: java.io.IOException: read failed, socket might closed or timeout, read ret: -1
at android.bluetooth.BluetoothSocket.readAll(BluetoothSocket.java:741)
at android.bluetooth.BluetoothSocket.readInt(BluetoothSocket.java:753)
W/System.err: at android.bluetooth.BluetoothSocket.connect(BluetoothSocket.java:375)
at com.example.main.BluetoothConnectionService$ConnectThread.run(BluetoothConnectionService.java:98)
I've had no luck troubleshooting this myself, any advice you may be able to give me is appreciated! It might be worth mentioning that this is my first time working with Bluetooth in android...
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.util.UUID;
public class BluetoothConnectionService {
private static final String TAG = "BluetoothConnectionService";
private static final String appName = "Bluetooth App";
private static final UUID uuid = UUID.fromString("8ce255c0-200a-11e0-ac64-0800200c9a66");
private final BluetoothAdapter mBluetoothAdapter;
private Context mcontext;
private AcceptThread mInsecureAcceptThread;
private ConnectThread mConnectThread;
private BluetoothDevice mmDevice;
private UUID deviceUUID;
private ConnectedThread mConnectedThread;
public BluetoothConnectionService(Context context){
this.mcontext = context;
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
start();
}
private class AcceptThread extends Thread{
private final BluetoothServerSocket mmServerSocket;
public AcceptThread() {
BluetoothServerSocket temp = null;
try {
temp = mBluetoothAdapter.listenUsingInsecureRfcommWithServiceRecord(appName, uuid);
Log.d(TAG,"AcceptThread: Setting up Server using: " + uuid);
} catch (IOException e) {
Log.e(TAG,"AcceptThread: IOException: " + e.getMessage());
}
mmServerSocket = temp;
}
public void run(){
Log.d(TAG,"run: AcceptThread Running.");
BluetoothSocket socket = null;
try {
socket = mmServerSocket.accept();
Log.d(TAG, "run: RFCOM server socket accepted connection.");
} catch (IOException e) {
Log.e(TAG,"RunThread: IOException: " + e.getMessage());
}
if(socket != null){
connected(socket,mmDevice);
}
}
public void cancel(){
try{
mmServerSocket.close();
} catch (IOException e) {
Log.e(TAG,"cancel: Close of AcceptThread ServerSocket failed. " + e.getMessage());
}
}
}
private class ConnectThread extends Thread{
private BluetoothSocket mmSocket;
public ConnectThread(BluetoothDevice device,UUID uuid){
mmDevice = device;
deviceUUID = uuid;
}
public void run(){
BluetoothSocket tmp = null;
Log.i(TAG,"Run mConnectThread");
try {
tmp = mmDevice.createInsecureRfcommSocketToServiceRecord(deviceUUID);
} catch (IOException e) {
Log.e(TAG,"could not create insecureRFcommSocket" + e.getMessage());
}
mmSocket = tmp;
mBluetoothAdapter.cancelDiscovery();
try {
mmSocket.connect();
Log.d(TAG,"run: Socket connected");
} catch (IOException e) {
e.printStackTrace();
try{
mmSocket.close();
Log.d(TAG,"run: Closed Socket");
} catch (IOException ex) {
Log.e(TAG,"Socket Connection failed to close.");
}
}
connected(mmSocket,mmDevice);
}
public void cancel(){
try{
Log.d(TAG,"cancel: Closing Client Socket");
mmSocket.close();
} catch (IOException e) {
Log.e(TAG,"cancel: close() of mmSocket in ConnectThread failed. " + e.getMessage());
}
}
}
public synchronized void start(){
Log.d(TAG,"start");
if(mConnectThread != null){
mConnectThread.cancel();
mConnectThread = null;
}
if(mInsecureAcceptThread == null){
mInsecureAcceptThread = new AcceptThread();
mInsecureAcceptThread.start();
}
}
public void startclient(BluetoothDevice device, UUID uuid){
Log.d(TAG, "startclient: Started");
Log.d(TAG,"Connecting Bluetooth");
mConnectThread = new ConnectThread(device,uuid);
mConnectThread.start();
}
private class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket) {
Log.d(TAG, "ConnectedTrhead: Starting");
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
Log.d(TAG,"Bluetooth Connected");
try {
tmpIn = mmSocket.getInputStream();
tmpOut = mmSocket.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
this.mmInStream = tmpIn;
this.mmOutStream = tmpOut;
}
public void run(){
byte[] buffer = new byte[1024];
int bytes;
while(true){
try {
bytes = mmInStream.read(buffer);
String incomingMessage = new String(buffer, 0 ,bytes);
Log.d(TAG,"Input Stream" + incomingMessage);
Intent incomingMessageIntent = new Intent("incomingMessage");
incomingMessageIntent.putExtra("themessage",incomingMessage);
LocalBroadcastManager.getInstance(mcontext).sendBroadcast(incomingMessageIntent);
} catch (IOException e) {
Log.e(TAG,"write: Error writing to inputstream" + e.getMessage());
break;
}
}
}
public void write(byte[] bytes){
String text = new String(bytes, Charset.defaultCharset());
try {
mmOutStream.write(bytes);
} catch (IOException e) {
Log.e(TAG,"write: Error writing to outputstream" + e.getMessage());
}
}
public void cancel(){
try{
mmSocket.close();
} catch (IOException e) {
Log.e(TAG,"Socket should not be closed");
}
}
}
private void connected(BluetoothSocket mmSocket, BluetoothDevice mmDevice){
Log.d(TAG,"connected: Starting.");
mConnectedThread = new ConnectedThread(mmSocket);
mConnectedThread.start();
}
public void write(byte[] out){
ConnectedThread r;
mConnectedThread.write(out);
}
}```

Android Studio - Issue connecting with device resulting in the socket getting closed

I am attempting to create an android app that connects to an Bluetooth device and am struggling with connecting.When running the run() method when I try to connect it does not work and goes to the catch portion of the code giving me the output of "socket closed". i am not sure why the try is not working.
I am aware that my code has several flaws, i am on my 5th day of android developing, however any help I could get would be greatly appreciated. The big problem I need to fix is being able to connect to the device and ultimately being able to receive a stream of data from it.
public class BluetoothConnection extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
byte[] buffer;
BluetoothAdapter mmAdapter;
// Unique UUID for this application, you may use different
private static final UUID MY_UUID = UUID
.fromString("eb58f747-a241-4ccb-935d-04ac6039895d");
public BluetoothConnection(BluetoothDevice device) {
BluetoothSocket tmp = null;
mmAdapter = null;
System.out.println("\n\n\n\n\n\n print is working? \n\n\n\n\n\n");
// Get a BluetoothSocket for a connection with the given BluetoothDevice
try {
tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) {
e.printStackTrace();
}
mmSocket = tmp;
//now make the socket connection in separate thread to avoid FC
Thread connectionThread = new Thread(new Runnable() {
#Override
public void run() {
// Always cancel discovery because it will slow down a connection
Log.d("workkkkkk","$$$$$$$$$$$$$$$$****** printingggggg ******$$$$$$$$$$$$$$$$");
//mmAdapter.cancelDiscovery();
}
});
connectionThread.start();
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the BluetoothSocket input and output streams
try {
try {
// This is a blocking call and will only return on a
// successful connection or an exception
mmSocket.connect();
System.out.println("\n\n\n\n\n\n socket connected\n\n\n\n\n\n");
} catch (IOException e) {
//connection to device failed so close the socket
try {
mmSocket.close();
System.out.println("\n\n\n\n\n\n socket closed\n\n\n\n\n\n");
} catch (IOException e2) {
System.out.println("\n\n\n\n\n\n in catch\n\n\n\n\n\n");
e2.printStackTrace();
}
}
tmpIn = mmSocket.getInputStream();
tmpOut = mmSocket.getOutputStream();
buffer = new byte[1024];
} catch (IOException e) {
e.printStackTrace();
}
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
// Keep listening to the InputStream while connected
while (true) {
try {
//read the data from socket stream
if(mmInStream != null) {
mmInStream.read(buffer);
}
// Send the obtained bytes to the UI Activity
} catch (IOException e) {
//an exception here marks connection loss
//send message to UI Activity
break;
}
}
}
public void write(byte[] buffer) {
try {
//write the data to socket stream
if(mmOutStream != null)
mmOutStream.write(buffer);
} catch (IOException e) {
e.printStackTrace();
}
}
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
This is being run in my DeviceList Class which is here. I am running into multiple problems here but the big one is pertaining to the BluetoothConnection.java however i am not sure if the issue is happening because of this class.
package com.example.curie.fairbanks_01;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothSocket;
import android.app.Activity;
import android.os.Bundle;
import java.io.IOException;
import android.util.Log;
import android.view.View;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.PopupMenu;
import android.widget.Switch;
import android.widget.Toast;
import android.content.Intent;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Set;
import java.util.UUID;
public class DeviceList extends Activity {
Button deviceSearch;
Switch btSwitch;
private BluetoothAdapter BA;
private Set<BluetoothDevice>pairedDevices;
private String instrumentName;
private UUID instrumentUUID;
BluetoothSocket socket;
BluetoothConnection connector;
ListView lv;
public static BluetoothDevice instrument;
PopupMenu pMenu;
ArrayList<MenuItem> popupList;
ArrayList<BluetoothDevice> list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_device_list);
deviceSearch = (Button) findViewById(R.id.device_search);
deviceSearch.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
PopupMenu popup = new PopupMenu(DeviceList.this, findViewById(R.id.device_search));
pairedDevices = BA.getBondedDevices();
list = new ArrayList<BluetoothDevice>();
for (BluetoothDevice bt : pairedDevices) {
list.add(bt);
popup.getMenu().add(bt.getName());
popup.show();
}
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
ArrayList<BluetoothDevice> deviceArrayList = new ArrayList<BluetoothDevice>(pairedDevices);
Toast.makeText(DeviceList.this, "Testing: " + item.getTitle(), Toast.LENGTH_SHORT).show();
// instrument = deviceArrayList.get(deviceArrayList.indexOf(item.getItemId()));
instrument = deviceArrayList.get(0);
connector = new BluetoothConnection(instrument);
connector.run();
Toast.makeText(DeviceList.this, "Connected to : " + item.getTitle(), Toast.LENGTH_SHORT).show();
Intent myIntent = new Intent(DeviceList.this, InputActivity.class);
DeviceList.this.startActivity(myIntent);
return true;
}
});
}
});
btSwitch = (Switch) findViewById(R.id.switch1);
BA =BluetoothAdapter.getDefaultAdapter();
lv =(ListView) findViewById(R.id.listView);
if(BA.isEnabled())
btSwitch.setChecked(true);
else
btSwitch.setChecked(false);
// pMenu = new PopupMenu(this,findViewById(R.id.device_search));
}
public void list(View v){
// pairedDevices = BA.getBondedDevices();
//
// ArrayList list = new ArrayList();
//
// for(BluetoothDevice bt : pairedDevices){
//
// list.add(bt.getName());
// pMenu.getMenu().add(bt.toString());
// }
Toast.makeText(getApplicationContext(), "Showing Paired Devices",Toast.LENGTH_SHORT).show();
final ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1, list);
lv.setAdapter(adapter);
}
public void onOff(View v)
{
if(BA.isEnabled())
{
BA.disable();
Toast.makeText(getApplicationContext(), " BT Turned off" ,Toast.LENGTH_LONG).show();
}
else
{ BA.enable();
Toast.makeText(getApplicationContext(), "BT Turned on" ,Toast.LENGTH_LONG).show();
}
}
public static BluetoothDevice getInstrument() {
return instrument;
}
}
this is what is running on the console when I select the device I would like to connect to:
I/System.out: $$$$$$$$$$$$$$$$****** in constructor ******$$$$$$$$$$$$$$$$
D/workkkkkk: $$$$$$$$$$$$$$$$****** printingggggg ******$$$$$$$$$$$$$$$$
D/BluetoothUtils: isSocketAllowedBySecurityPolicy start : device null
D/BluetoothSocket: connect(): myUserId = 0
W/BluetoothAdapter: getBluetoothService() called with no BluetoothManagerCallback
I/System.out: $$$$$$$$$$$$$$$$****** socket closed ******$$$$$$$$$$$$$$$$
D/BluetoothSocket: getInputStream(): myUserId = 0
getOutputStream(): myUserId = 0
Why is it not connecting in the try?

Manage Bluetooth Communication

Im actually trying to interact with a bluetooth module controlled by a microcontroller PIC.
So i need to build an android app in order to send caracters by bluetooth.
But im kind of lost.
The beginning is quiet clear to me ( enabling bluetooth and connect as client)
But i dont know how to interact with my Bluetooth Service class from my MainActivity.
How to interact with write and read.
I can see that im successfully Connected to my device.
ALEA is the name of the BT module i want to connect to.
Thanks for your help
package com.example.stef.bluetoothencore;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Set;
import java.util.UUID;
public class MainActivity extends AppCompatActivity {
private BluetoothAdapter mBluetoothAdapter;
ArrayList<BluetoothDevice> arrayListBluetoothDevices = null;
ArrayList<String> NomBT=null;
BluetoothDevice mydevice;
int position_alea=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView lv=(ListView)findViewById(R.id.listdevice);
CheckBox Aleabox=(CheckBox) findViewById(R.id.checkAlea);
arrayListBluetoothDevices = new ArrayList<BluetoothDevice>();
NomBT= new ArrayList<String>();
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
// Device does not support Bluetooth
}
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 1);
}
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
if (pairedDevices.size() > 0) {
for (BluetoothDevice device : pairedDevices) {
BluetoothDevice mDevice = device;
arrayListBluetoothDevices.add(device); // On charge la liste de Device
NomBT.add(device.getName().toString());
if(device.getName().toString().equals("ALEA")){
mydevice=device;
Aleabox.setChecked(true);
Aleabox.setText(mydevice.getName().toString());
}
}
}
final ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, NomBT);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
// position_alea=i;
//Toast.makeText(getApplicationContext(), mydevice.getName().toString(), Toast.LENGTH_SHORT).show();
ConnectThread mConnectThread = new ConnectThread(mydevice);
mConnectThread.start();
}
});
}
private class ConnectThread extends Thread {
private final BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;
private final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
public ConnectThread(BluetoothDevice device) {
BluetoothSocket tmp = null;
mmDevice = device;
try {
tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) { }
mmSocket = tmp;
}
public void run() {
mBluetoothAdapter.cancelDiscovery();
try {
mmSocket.connect();
} catch (IOException connectException) {
try {
mmSocket.close();
} catch (IOException closeException) { }
return;
}
ConnectedThread mConnectedThread = new ConnectedThread(mmSocket);
mConnectedThread.start();
mConnectedThread.write("c".getBytes());
}
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}
}
private class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket) {
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) { }
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
byte[] buffer = new byte[1024];
int begin = 0;
int bytes = 0;
while (true) {
try {
bytes += mmInStream.read(buffer, bytes, buffer.length - bytes);
for(int i = begin; i < bytes; i++) {
if(buffer[i] == "#".getBytes()[0]) {
mHandler.obtainMessage(1, begin, i, buffer).sendToTarget();
begin = i + 1;
if(i == bytes - 1) {
bytes = 0;
begin = 0;
}
}
}
} catch (IOException e) {
break;
}
}
}
public void write(byte[] bytes) {
try {
mmOutStream.write(bytes);
} catch (IOException e) { }
}
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}
}
Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
byte[] writeBuf = (byte[]) msg.obj;
int begin = (int)msg.arg1;
int end = (int)msg.arg2;
switch(msg.what) {
case 1:
String writeMessage = new String(writeBuf);
writeMessage = writeMessage.substring(begin, end);
break;
}
}
};
}
Up, im still blocked, i am connected to my device but i can't read or write data ...

What can I do by getBluetoothService() called with no BluetoothManagerCallback ?

hi I want to write a Android java application that can connect with a bluetooth device but I get the error:
W/BluetoothAdapter﹕ getBluetoothService() called with no BluetoothManagerCallback
I use a Nexus 5 device with android version 4.4.4
here is my code:
package com.example.tarasov.bluetoothexample;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Set;
import java.util.UUID;
import android.view.Menu;
import android.view.MenuItem;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class MyActivity extends Activity implements OnItemClickListener {
/*
* Deklaration
* */
ArrayAdapter<String> listAdapter;
ListView listView;
BluetoothAdapter btAdapter;
Set<BluetoothDevice> deviceArray;
ArrayList<String> pairedDevices;
ArrayList<BluetoothDevice> devices;
public static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
protected static final int SUCCESS_CONNECT = 0;
protected static final int MESSAGE_READ = 1;
IntentFilter filter;
BroadcastReceiver receiver;
String tag = "debugging";
Handler mHandler = new Handler(){
#Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
Log.i(tag, "in handler");
super.handleMessage(msg);
switch(msg.what){
case SUCCESS_CONNECT:
// DO something
ConnectedThread connectedThread = new ConnectedThread((BluetoothSocket)msg.obj);
Toast.makeText(getApplicationContext(), "CONNECT", Toast.LENGTH_SHORT).show();
String s = "successfully connected";
connectedThread.write(s.getBytes());
Log.i(tag, "connected");
break;
case MESSAGE_READ:
byte[] readBuf = (byte[])msg.obj;
String string = new String(readBuf);
Toast.makeText(getApplicationContext(), string, Toast.LENGTH_SHORT).show();
break;
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
init(); //Initialisierung der Komponenten
if(btAdapter==null)
{
Toast.makeText(getApplicationContext(), "Kein Bluetooth aktiviert", Toast.LENGTH_SHORT).show();
finish();
}
else
{
if (!btAdapter.isEnabled()){
turnOnBT();
}
getPairedDevices();
startDiscovery();
}
}
private void startDiscovery() {
btAdapter.cancelDiscovery();
btAdapter.startDiscovery();
}
private void turnOnBT() {
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(intent,1);
}
private void getPairedDevices() {
deviceArray = btAdapter.getBondedDevices();
if (deviceArray.size()>0){
for (BluetoothDevice device:deviceArray){
pairedDevices.add(device.getName());
}
}
}
private void init(){
listView = (ListView)findViewById(R.id.listView); //bindet ListView
listView.setOnItemClickListener(this);
listAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,0);
listView.setAdapter(listAdapter);
btAdapter = BluetoothAdapter.getDefaultAdapter();
pairedDevices = new ArrayList<String>();
filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
devices = new ArrayList<BluetoothDevice>();
receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)){
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
devices.add(device);
String s = "";
for (int a=0;a< pairedDevices.size();a++){
if (device.getName().equals(pairedDevices.get(a))){
s = "(Verbunden)";
break;
}
}
listAdapter.add(device.getName()+" "+s+" "+"\n"+device.getAddress());
}
else if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)){
}
else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)){
}
else if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)){
if (btAdapter.getState()==btAdapter.STATE_OFF){
turnOnBT();
}
}
}
};
registerReceiver(receiver,filter);
filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
registerReceiver(receiver,filter);
filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(receiver,filter);
filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
registerReceiver(receiver,filter);
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(receiver);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode==RESULT_CANCELED){
Toast.makeText(getApplicationContext(), "Bluetooth muss erst aktiviert werden", Toast.LENGTH_SHORT).show();
finish();
}
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
if (btAdapter.isDiscovering()){
btAdapter.cancelDiscovery();
}
if (listAdapter.getItem(arg2).contains("Verbunden")){
BluetoothDevice selectedDevice = devices.get(arg2);
ConnectThread connect = new ConnectThread(selectedDevice);
connect.start();
Log.i(tag, "in click listener");
}
else
{
Toast.makeText(getApplicationContext(), "Gerät ist nicht verbunden", Toast.LENGTH_SHORT).show();
}
}
/*
* Hilfsklassen
* */
private class ConnectThread extends Thread {
private final BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;
public ConnectThread(BluetoothDevice device) {
// Use a temporary object that is later assigned to mmSocket,
// because mmSocket is final
BluetoothSocket tmp = null;
mmDevice = device;
Log.i(tag, "construct");
// Get a BluetoothSocket to connect with the given BluetoothDevice
try {
// MY_UUID is the app's UUID string, also used by the server code
tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) {
Log.i(tag, "get socket failed");
}
mmSocket = tmp;
}
public void run() {
// Cancel discovery because it will slow down the connection
btAdapter.cancelDiscovery();
Log.i(tag, "connect - run");
try {
// Connect the device through the socket. This will block
// until it succeeds or throws an exception
mmSocket.connect();
Log.i(tag, "connect - succeeded");
} catch (IOException connectException) { Log.i(tag, "connect failed");
// Unable to connect; close the socket and get out
try {
mmSocket.close();
} catch (IOException closeException) { }
return;
}
// Do work to manage the connection (in a separate thread)
mHandler.obtainMessage(SUCCESS_CONNECT, mmSocket).sendToTarget();
}
/** Will cancel an in-progress connection, and close the socket */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}
}
private class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket) {
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the input and output streams, using temp objects because
// member streams are final
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) { }
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
byte[] buffer; // buffer store for the stream
int bytes; // bytes returned from read()
// Keep listening to the InputStream until an exception occurs
while (true) {
try {
// Read from the InputStream
buffer = new byte[1024];
bytes = mmInStream.read(buffer);
// Send the obtained bytes to the UI activity
mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer)
.sendToTarget();
} catch (IOException e) {
break;
}
}
}
/* Call this from the main activity to send data to the remote device */
public void write(byte[] bytes) {
try {
mmOutStream.write(bytes);
} catch (IOException e) { }
}
/* Call this from the main activity to shutdown the connection */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}
}

Android Application communication serial data

I am making a Bluetooth app which connects to a Bluetooth transmitter/receiver which is transmitting serial data. The Bluetooth device will eventually be connected to sensors and these sensors will provide data which needs to be displayed on my phone. As of now am using the simulation software CoolTerm to send data back and forth between my app and the external Bluetooth device. Currently I have successfully made the app detect and connect to devices. But I am running into some problems:
Firstly does any one know how to install CoolTerm( its available on Mac and windows technically speaking), but when I try to install it on Ubuntu it gives no executable file like it did on windows. Anyone who knows how to install this on ubuntu please provide me the steps I have already downloaded the Linux version tar ball from there website and unziped it.
Although on successful connection my app sends a string which is received by the Bluetooth device I am not able to receive data back. The way I have things currently set up I expect a toast message to pop-up telling me I have received data when the external Bluetooth device transmits to me. The CoolTerm software allows you to send data but this is for some reason not being displayed on my app. Any ideas?
Lastly anyone know a good text box widget or something I can use in my app to send data to the external Bluetooth device. Right now I have the app send a string as soon as it connects.
Here is a YouTube link: I have made some minor changes to this as the code will suggest.
Click [here](http://www.youtube.com/watch?v=r55C77_ohi8"youtube video of app")!
Click [here](https://drive.google.com/?tab=mo&authuser=0#folders/0BwRY4KO_k7sUSGpLX0o4TDFCOFk"cleaner code formmatt")!
Here is the code
package com.example.intellicyclemobileside;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.ToggleButton;
public class MainActivity extends Activity {
ToggleButton toggle_discovery;
Button button;
ListView listView;
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
ArrayAdapter<String> mArrayAdapter;
ArrayAdapter<String> adapter;
ArrayList<String> pairedDevicesList;
ArrayList<String> unpairedDevicesList;
ArrayList<String> combinedDevicesList;
Set<BluetoothDevice> pairedDevices;
Set<String> unpairedDevices;
BroadcastReceiver mReceiver;
String selectedFromList;
String selectedFromListName;
String selectedFromListAddress;
BluetoothDevice selectedDevice;
/*
public BluetoothSocket mmSocket;
public BluetoothDevice mmDevice;*/
protected static final int SUCCESS_CONNECT = 0;
protected static final int MESSAGE_READ = 1;
final int STATE_CONNECTED = 2;
final int STATE_CONNECTING = 1;
final int STATE_DISCONNECTED = 0;
private final UUID MY_UUID = UUID.fromString("0001101-0000-1000-8000-00805F9B34FB");
private static final int REQUEST_ENABLE_BT = 1;
Handler mHandler = new Handler(){
public void handleMessage(Message msg){
super.handleMessage(msg);
switch(msg.what){
case SUCCESS_CONNECT:
// Do Something;
ConnectedThread connectedThread = new ConnectedThread((BluetoothSocket)msg.obj);
Toast.makeText(getApplicationContext(),"CONNECTED",0).show();
String s = "This string proves a socket connection has been established!!";
connectedThread.write(s.getBytes());
break;
case MESSAGE_READ:
byte[] readBuf = (byte[])msg.obj;
String string = new String(readBuf);
Toast.makeText(getApplicationContext(),string,0).show();
break;
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.findDevices);
toggle_discovery = (ToggleButton) findViewById(R.id.deviceDiscoverable);
pairedDevicesList = new ArrayList<String>();
unpairedDevicesList = new ArrayList<String>();
unpairedDevices = new HashSet<String>();
listView = (ListView)findViewById(R.id.listView);
// Sets up Bluetooth
enableBT();
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
Toast.makeText(getApplicationContext(), "Searching for devices, please wait... ",Toast.LENGTH_SHORT).show();
// Checks for known paired devices
pairedDevices = mBluetoothAdapter.getBondedDevices();
displayCominedDevices();
//mBluetoothAdapter.cancelDiscovery();
}
});
toggle_discovery.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
makeDicoverable(1);
} else {
// The toggle is disabled
makeDicoverable(0);
}
}
});
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
// When clicked, show a toast with the TextView text
selectedFromList = (String) (listView.getItemAtPosition(position));
/*Debugging
Toast.makeText(getApplicationContext(), selectedFromList,Toast.LENGTH_SHORT).show();*/
String[] parts = selectedFromList.split(" ");
selectedFromListName = parts[0];
selectedFromListAddress = parts[1];
BluetoothDevice selectedDevice = selectedDevice(selectedFromListAddress);
mBluetoothAdapter.cancelDiscovery();
ConnectThread ct = new ConnectThread(selectedDevice);
ct.start();
//ConnectThread ConnectThread = new ConnectThread(selectedDevice);
//connectDevice();
/* Debug Help
Toast.makeText(getApplicationContext(), selectedFromListName,Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(), selectedFromListAddress,Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(),selectedDevice.getAddress(), Toast.LENGTH_SHORT).show();*/
}
});
}
public void displayCominedDevices(){
displayPairedDevices();
displayDetectedDevices();
mArrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,removeDuplicates(unpairedDevicesList,pairedDevicesList));
listView.setAdapter(mArrayAdapter);
}
public BluetoothDevice selectedDevice(String deviceAddress){
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
BluetoothDevice device;
device = mBluetoothAdapter.getRemoteDevice(deviceAddress);
return device;
}
#SuppressLint("NewApi")
public String checkState(BluetoothSocket mmSocket2){
String state = "NOT_KNOWN";
if (mmSocket2.isConnected() == true){
state = "STATE_CONNECTED";
}
state = "STATE_DISCONNECTED";
Toast.makeText(getApplicationContext(), state, Toast.LENGTH_SHORT).show();
return state;
}
#SuppressWarnings("unchecked")
public ArrayList<String> removeDuplicates(ArrayList<String> s1, ArrayList<String> s2){
/*Debugging
Toast.makeText(getApplication(), "unpairedList " + s1.toString(),Toast.LENGTH_LONG).show();
Toast.makeText(getApplication(), "pairedList " + s2.toString(),Toast.LENGTH_LONG).show(); */
combinedDevicesList = new ArrayList<String>();
combinedDevicesList.addAll(s1);
combinedDevicesList.addAll(s2);
#SuppressWarnings("unchecked")
Set Unique_set = new HashSet(combinedDevicesList);
combinedDevicesList = new ArrayList<String>(Unique_set);
/*Debugging
Toast.makeText(getApplication(),"Combined List" + combinedDevicesList.toString(),Toast.LENGTH_LONG).show(); */
return combinedDevicesList;
}
public void enableBT(){
if (mBluetoothAdapter == null) {
// Device does not support Bluetooth
Toast.makeText(getApplicationContext(), "Bluetooth is not suppourted on Device",Toast.LENGTH_SHORT).show();
}
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
int resultCode = Activity.RESULT_OK;
if(resultCode < 1){
Toast.makeText(getApplicationContext(), "Please Accept Enabling Bluetooth Request!", Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(getApplicationContext(), "Enabling Bluetooth FAILED!", Toast.LENGTH_SHORT).show();
}
}
}
public void displayPairedDevices(){
// If there are paired devices
enableBT();
if (pairedDevices.size() > 0) {
//Toast.makeText(getApplicationContext(),"in loop",Toast.LENGTH_SHORT).show();
// Loop through paired devices
for (BluetoothDevice device : pairedDevices) {
// Add the name and address to an array adapter to show in a ListView
String s = " ";
String deviceName = device.getName();
String deviceAddress = device.getAddress();
pairedDevicesList.add(deviceName + s + deviceAddress +" \n");
//listView.setAdapter(mArrayAdapter);
//Toast.makeText(getApplicationContext(), device.getName(),Toast.LENGTH_SHORT).show();
}
/*
mArrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,pairedDevicesList);
listView.setAdapter(mArrayAdapter);*/
}
}
public void displayDetectedDevices(){
mBluetoothAdapter.startDiscovery();
// Create a BroadcastReceiver for ACTION_FOUND
mReceiver = new BroadcastReceiver() {
#SuppressWarnings("static-access")
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
/* Debugging help
Toast.makeText(getApplicationContext(),action,Toast.LENGTH_SHORT).show();*/
// When discovery finds a device
if(BluetoothDevice.ACTION_FOUND.equals(action)){
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
/* Debugging help
Toast.makeText(getApplicationContext(),device.getName(),Toast.LENGTH_SHORT).show();*/
String deviceName = device.getName();
String deviceAddress = device.getAddress();
String s = " ";
unpairedDevices.add(deviceName + s + deviceAddress +" \n");
//unpairedDevicesList.add(deviceName + s + deviceAddress +" (un-paired)\n");
unpairedDevicesList = new ArrayList<String>(unpairedDevices);
}
}
};
/*adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,unpairedDevicesList);
listView.setAdapter(adapter);*/
// Register the BroadcastReceiver
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter); // Don't forget to unregister during onDestroy
//Toast.makeText(getApplicationContext(), unpairedDevicesList.toString(), Toast.LENGTH_LONG).show();
}
public void makeDicoverable(int option){
Intent discoverableIntent;
if (option == 1){
discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,120);
startActivity(discoverableIntent);
Toast.makeText(getApplicationContext(), "Open discovery for 2mins", Toast.LENGTH_SHORT).show();
} else {
discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 1);
startActivity(discoverableIntent);
Toast.makeText(getApplicationContext(), "Open discovery is OFF!", Toast.LENGTH_SHORT).show();
}
}
/*Un-used Method
public void compareAddress(BluetoothDevice checkDevice,String address){
if((checkDevice.getAddress().equals(address))){
selectedDevice = checkDevice;
}
}*/
#SuppressLint("NewApi")
public class ConnectThread extends Thread {
private final BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;
public ConnectThread(BluetoothDevice device) {
// Use a temporary object that is later assigned to mmSocket,
// because mmSocket is final
BluetoothSocket tmp = null;
mmDevice = device;
// Get a BluetoothSocket to connect with the given BluetoothDevice
try {
// MY_UUID is the app's UUID string, also used by the server code
tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) { }
mmSocket = tmp;
}
public void run() {
// Cancel discovery because it will slow down the connection
mBluetoothAdapter.cancelDiscovery();
try {
// Connect the device through the socket. This will block
// until it succeeds or throws an exception
mmSocket.connect();
} catch (IOException connectException) {
// Unable to connect; close the socket and get out
try {
mmSocket.close();
} catch (IOException closeException) {
Toast.makeText(getApplicationContext(), "Connecting to device failed!", Toast.LENGTH_LONG).show();
}
return;
}
// Do work to manage the connection (in a separate thread)
mHandler.obtainMessage(SUCCESS_CONNECT, mmSocket).sendToTarget();
}
/** Will cancel an in-progress connection, and close the socket */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}
}
private class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket) {
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the input and output streams, using temp objects because
// member streams are final
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) { }
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
byte[] buffer; // buffer store for the stream
int bytes; // bytes returned from read()
// Keep listening to the InputStream until an exception occurs
while (true) {
try {
// Read from the InputStream
buffer = new byte[1024];
bytes = mmInStream.read(buffer);
// Send the obtained bytes to the UI activity
mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer).sendToTarget();
} catch (IOException e) {
break;
}
}
}
/* Call this from the main activity to send data to the remote device */
public void write(byte[] bytes) {
try {
mmOutStream.write(bytes);
} catch (IOException e) { }
}
}
}
If your device is a 'Bluetooth to UART converter' module, then, make a loop-back connection at module (i.e. short TXD with RXD). Send test strings from your app to the module and expect to receive it back as well. Depending on results of such test your app or/and module can be probed further to recover real issue, if any.

Categories

Resources