Android: Bluetooth Trouble opening server socket - java

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

Related

Trying to use bluetooth, but lack understanding of handler

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.

Android input Stream doesn't receive any message

I'm trying to receive data from Bluetooth which is connected to arduino ,but when I read from the input stream it keep giving me bytes=0
this is my code for Bluetooth service :
package com.example.googlemapproject;
import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.os.SystemClock;
import android.speech.tts.TextToSpeech;
import android.support.annotation.Nullable;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Locale;
import java.util.UUID;
import java.util.Vector;
public class BluetoothService extends Service {
TextToSpeech txt_to_speech;
private BluetoothAdapter mBluetoothAdapter;
public static final String B_UUID = "00001101-0000-1000-8000-00805f9b34fb";
public static final int STATE_NONE = 0;
public static final int STATE_CONNECTING = 2;
private ConnectBtThread mConnectThread;
private static ConnectedBtThread mConnectedThread;
private static Handler mHandler = null;
public static int mState = STATE_NONE;
public static BluetoothDevice sDevice = null;
public Vector<Byte> packData = new Vector<>(2048);
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
public void toast(String mess){
Toast.makeText(this,mess,Toast.LENGTH_SHORT).show();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
String deviceg = intent.getStringExtra("bluetooth_device");
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
connectToDevice(deviceg);
return START_STICKY;
}
private synchronized void connectToDevice(String macAddress){
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice("00:13:EF:00:E3:77");
if (mState == STATE_CONNECTING){
if (mConnectThread != null){
mConnectThread.cancel();
mConnectThread = null;
}
}
if (mConnectedThread != null){
mConnectedThread.cancel();
mConnectedThread = null;
}
mConnectThread = new ConnectBtThread(device);
toast("connecting");
mConnectThread.start();
setState(STATE_CONNECTING);
}
private void setState(int state){
mState = state;
if (mHandler != null){
// mHandler.obtainMessage();
}
}
public synchronized void stop(){
setState(STATE_NONE);
if (mConnectThread != null){
mConnectThread.cancel();
mConnectThread = null;
}
if (mConnectedThread != null){
mConnectedThread.cancel();
mConnectedThread = null;
}
if (mBluetoothAdapter != null){
mBluetoothAdapter.cancelDiscovery();
}
stopSelf();
}
public void sendData(String message){
if (mConnectedThread!= null){
mConnectedThread.write(message.getBytes());
toast("sent data");
}else {
Toast.makeText(BluetoothService.this,"Failed to send data",Toast.LENGTH_SHORT).show();
}
}
#Override
public boolean stopService(Intent name) {
setState(STATE_NONE);
if (mConnectThread != null){
mConnectThread.cancel();
mConnectThread = null;
}
if (mConnectedThread != null){
mConnectedThread.cancel();
mConnectedThread = null;
}
mBluetoothAdapter.cancelDiscovery();
return super.stopService(name);
}
/*private synchronized void connected(BluetoothSocket mmSocket){
if (mConnectThread != null){
mConnectThread.cancel();
mConnectThread = null;
}
if (mConnectedThread != null){
mConnectedThread.cancel();
mConnectedThread = null;
}
mConnectedThread = new ConnectedBtThread(mmSocket);
mConnectedThread.start();
setState(STATE_CONNECTED);
}*/
private class ConnectBtThread extends Thread{
private final BluetoothSocket mSocket;
private final BluetoothDevice mDevice;
public ConnectBtThread(BluetoothDevice device){
mDevice = device;
BluetoothSocket socket = null;
try {
socket = device.createInsecureRfcommSocketToServiceRecord(UUID.fromString(B_UUID));
} catch (IOException e) {
e.printStackTrace();
}
mSocket = socket;
}
#Override
public void run() {
mBluetoothAdapter.cancelDiscovery();
try {
mSocket.connect();
Log.d("service","connect thread run method (connected)");
SharedPreferences pre = getSharedPreferences("BT_NAME",0);
pre.edit().putString("bluetooth_connected",mDevice.getName()).apply();
} catch (IOException e) {
try {
mSocket.close();
Log.d("service","connect thread run method ( close function)");
} catch (IOException e1) {
e1.printStackTrace();
}
e.printStackTrace();
}
//connected(mSocket);
mConnectedThread = new ConnectedBtThread(mSocket);
mConnectedThread.start();
}
public void cancel(){
try {
mSocket.close();
Log.d("BT","connect thread cancel method");
} catch (IOException e) {
e.printStackTrace();
}
}
}
private class ConnectedBtThread extends Thread{
private final BluetoothSocket cSocket;
private final InputStream inS;
private final OutputStream outS;
private byte[] buffer;
public ConnectedBtThread(BluetoothSocket socket){
cSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
try {
tmpIn = socket.getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
try {
tmpOut = socket.getOutputStream();
Log.d("BT","OUTPUT STREAM");
} catch (IOException e) {
e.printStackTrace();
}
inS = tmpIn;
outS = tmpOut;
}
#Override
public void run() {
// Looper.prepare();
Log.d("BT","REading FROM IS");
int bytesAvailable = 0;
try {
bytesAvailable = inS.available();
Log.d("BT","REading FROM IS");
} catch (IOException e) {
e.printStackTrace();
}
byte[] buffer = new byte[bytesAvailable];
int bytes;
Log.d("BT","REading #BYTES");
while (true) {
try {try {
sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
bytes = inS.read(buffer);
Log.d("BT",String.valueOf(bytes));
final String strReceived = new String(buffer, 0, bytes);
// Log.d("BT",strReceived);
} catch (IOException e) {
e.printStackTrace();
}}
}
private void cancel(){
try {
cSocket.close();
Log.d("service","connected thread cancel method");
} catch (IOException e) {
e.printStackTrace();
}
}
}
#Override
public void onDestroy() {
this.stop();
super.onDestroy();
}
}
I tried another app and the data from Bluetooth is received correctly so the problem is not in the Bluetooth,also I tried to put sleep while reading but it didn't work too

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) { }
}
}

Categories

Resources