Android input Stream doesn't receive any message - java

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

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

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

Reconnecting to Bluetooth in android / Reading after Reconnect

I have a program that establishes a Bluetooth connection, reads the InputStream to a textView, and can disconnect from the module. While I can successfully disconnect and reconnect to the module (HC-05) as many times as I please, I can't get an InputStream read anymore after I reconnect. I believe it is because I don't know how to reinitialize the thread I'm using to read the InputStream. I am very new to java and android programming, any help with this issue would be appreciated.This is my code:
The textView for the read display is called 'Status' and I am hoping to "reset" the thread upon the onclick connect().
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Set;
public class MainActivity extends AppCompatActivity implements Runnable {
private BluetoothAdapter adapter;
private InputStream inputStream;
private OutputStream outputStream;
private Thread thread;
private TextView Status;
private TextView Connection;
private BluetoothSocket socket = null;
private boolean threadStatusInitial=true;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Status=(TextView) findViewById(R.id.StatusID);
Connection=(TextView) findViewById(R.id.ConnectionStatus);
adapter= BluetoothAdapter.getDefaultAdapter();
if(adapter==null){
Toast.makeText(this,"bluetooth is unavailable",Toast.LENGTH_SHORT).show();
finish();
return;
}
thread=new Thread(this);
}
public void connect(View view){
Set<BluetoothDevice> devices=adapter.getBondedDevices();
for(BluetoothDevice device:devices){
if(device.getName().startsWith("HC-05")){
try {
socket=device.createRfcommSocketToServiceRecord(device.getUuids()[0].getUuid());
socket.connect();
Connection.setText("Connected");
inputStream=socket.getInputStream();
outputStream=socket.getOutputStream();
if (threadStatusInitial){
thread.start();
threadStatusInitial=false; //this ensures that the thread.start() method will only be called during the first connection
}
} catch (IOException e) {
Toast.makeText(this,"Can't Connect",Toast.LENGTH_LONG).show();
e.printStackTrace();
}
break;
}
}
}
public void Disconnect(View view) throws InterruptedException {
if (inputStream != null) {
try {inputStream.close();} catch (Exception e) {}
inputStream = null;
}
if (outputStream != null) {
try {outputStream.close();} catch (Exception e) {}
outputStream = null;
}
if (socket != null) {
try {socket.close();} catch (Exception e) {Toast.makeText(this,"Can't Connect",Toast.LENGTH_LONG).show();}
socket = null;
}
Connection.setText("Disconnected");
}
#Override
public void run() {
String textInput = "hi";
byte[] writeBytes=textInput.getBytes();
if(outputStream!=null){
try {
outputStream.write(writeBytes);
} catch (IOException e) {
Toast.makeText(this,"Unable to Write to Bluetooth ",Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
while(inputStream!=null){
byte [] buffer=new byte[2048];
try {
int length=inputStream.read(buffer);
final String strReceived = new String(buffer, 0, length);
runOnUiThread(new Runnable(){
#Override
public void run() {
Status.setText(strReceived);
}});
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

I can't send the data through Bluetooth

I wrote the application in Android Studio which has to send 1 on Arduino Pro Mini. Data is sent but doesn't reach Arduino. I checked Arduino through Bluetooth Terminal and everything was OK so the problem is in code. What is wrong?
package com.example.niko.motoco;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.io.OutputStream;
import java.util.UUID;
public class MainActivity extends AppCompatActivity {
BluetoothAdapter btAdapter = null ;
BluetoothDevice btDevice = null;
BluetoothSocket btSocket = null;
final String LOG_TAG = "myLogs";
Button btConnect, btSend;
public TextView checkText;
private static final int REQUEST_ENABLE_BT = 1;
private static final int CONNECTEDdevice = 2;
Boolean connection = false;
private static String MAC = null;
UUID my_UUID = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");
private ConnectedThread MyThread = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
checkText = (TextView) findViewById(R.id.checkText);
btConnect = (Button)findViewById(R.id.btConnect);
btSend = (Button)findViewById(R.id.btSend);
btAdapter = BluetoothAdapter.getDefaultAdapter();
if (btAdapter == null) {
Toast.makeText(getApplicationContext(),"Device does not support Bluetooth",Toast.LENGTH_LONG).show();
} else if (!btAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
btConnect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (connection) {
// disconnect
try {
btSocket.close();
connection = false;
btConnect.setText("Connect");
Toast.makeText(getApplicationContext(),"Bluetooht is disconnected:",Toast.LENGTH_LONG).show();
} catch (IOException error) {
Toast.makeText(getApplicationContext(),"Error;" + error,Toast.LENGTH_LONG).show();
}
} else {
// connect
Intent ListDevices = new Intent(MainActivity.this, ListDevices.class);
startActivityForResult(ListDevices,CONNECTEDdevice);
}
}
});
btSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
MyThread.write((byte) 1);
Toast.makeText(getApplicationContext(),"Sending 1",Toast.LENGTH_LONG).show();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case REQUEST_ENABLE_BT:
if(resultCode == Activity.RESULT_OK) {
Toast.makeText(getApplicationContext(),"bluetooth is activated",Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(),"bluetooth is not activated",Toast.LENGTH_LONG).show();
finish();
}
break;
case CONNECTEDdevice :
if (resultCode == Activity.RESULT_OK) {
MAC = data.getExtras().getString(ListDevices.MACaddress);
btDevice = btAdapter.getRemoteDevice(MAC);
try {
btSocket = btDevice.createRfcommSocketToServiceRecord(my_UUID);
btSocket.connect();
connection = true;
btConnect.setText("Disconnect");
Toast.makeText(getApplicationContext(),"MAC of connected device:" + MAC,Toast.LENGTH_LONG).show();
MyThread = new ConnectedThread(btSocket);
//MyThread.start();
} catch (IOException error) {
connection = false;
Toast.makeText(getApplicationContext(),"Error:" + error,Toast.LENGTH_LONG).show();
}
}else {
Toast.makeText(getApplicationContext(),"didn't get MAC",Toast.LENGTH_LONG).show();
}
}
}
private class ConnectedThread extends Thread {
private final BluetoothSocket btSocket2;
private final OutputStream OutStream;
public ConnectedThread(BluetoothSocket socket) {
btSocket2 = socket;
OutputStream tmpOut = null;
try {
tmpOut = socket.getOutputStream();
} catch (IOException e) { }
OutStream = tmpOut;
}
public void write(byte bytes) {
try {
OutStream.write(bytes);
} catch (IOException e) { }
}
public void cancel() {
try {
btSocket2.close();
} catch (IOException e) { }
}
}
}
What's wrong ? At least those 2 pieces of code are wrong :
try {
tmpOut = socket.getOutputStream();
} catch (IOException e) { }
And later:
try {
OutStream.write(bytes);
} catch (IOException e) { }
When something goes wrong you catch the exception silently and loose all chances to identify the root cause.
Change the code to something like this :
try {
tmpOut = socket.getOutputStream();
} catch (IOException e) {
Log.(TAG, "Fail to get socket output stream" ,e);
}
And later :
try {
OutStream.write(bytes);
} catch (IOException e) {
Log.(TAG, "Fail to write on socket output stream" ,e);
}
Then re-run your code and look at the logcat. You will probably see the cause of your problems.

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