Send String via bluetooth OnClick() - android

I am trying to send String message via Bluetooh. I am using code from this post:send message
I would like to send message on OnClick() to another connected device. Currently i can display paired devices and i am able to connect with them.
P.S I am trying to send message in write() function. When i tried to debug the code, i've figured out that debugger don't enter toMESSAGE WRITE on MESSAGE READ statement. Thanks for any help.
public class BluetoothActivity extends AppCompatActivity {
public static final int REQUEST_ENABLE_BT=1;
ListView lv_paired_devices;
Button sendMessage;
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);
Log.i("TAGREAD", "Bluetooth not supported");
Toast.makeText(getApplicationContext(),string_recieved,Toast.LENGTH_LONG).show();
//do some task based on recieved string
break;
case MESSAGE_WRITE:
if(msg_type.obj!=null){
ConnectedThread connectedThread=new ConnectedThread((BluetoothSocket)msg_type.obj);
connectedThread.write(bluetooth_message.getBytes());
Log.i("TAGWRITE", "Bluetooth not supported");
}
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(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().setTitle("Sparowane urzÄ…dzenia");
bluetoothAdapter=BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter == null) {
Log.i("TAGTAG", "Bluetooth not supported");
// Show proper message here
finish();
}
else{
setContentView(R.layout.activity_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);
sendMessage=findViewById(R.id.send_button);
}
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();
Toast.makeText(BluetoothActivity.this,bytes,Toast.LENGTH_LONG).show();
} catch (IOException e) {
break;
}
}
}
/* Call this from the main activity to send data to the remote device */
public void write(byte[] bytes) {
sendMessage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
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) { }
}
}

Related

how to solve bluetooth connect() fails socket might be close

I'm trying to make an app that communicates with nearby devices.
My app is composed of the main activity that asks to enable bluetooth and sets the discoverable mode, so it waits for a connection to be made.
The second activity takes care of finding nearby devices and making the pairing.
After pairing pairing some configuration messages are exchanged and then both start a ThirdActivity that deals with the communication between the two devices.
I can successfully exchange these messages but the problem is that I need to pass the BluetoothService object (which keeps the communication information) to the Third Activity.
Since I don't think I can implement parcelable then I simply closed the connection without eliminating the pairing and then recreate AcceptThread and ConnectThread in the thirdActivity by creating a new BluetoothService object but always passing the same BluetoothDevice.
From the various logs what happens is that the AcceptThread waits on the accept(), while the ConnectThread fails the connect() reporting this error.
W/System.err: java.io.IOException: read failed, socket might closed or timeout, read ret: -1
at android.bluetooth.BluetoothSocket.readAll(BluetoothSocket.java:762)
at android.bluetooth.BluetoothSocket.readInt(BluetoothSocket.java:776)
at android.bluetooth.BluetoothSocket.connect(BluetoothSocket.java:399)
at com.crossthebox.progetto.BluetoothService$ConnectThread.run(BluetoothService.java:118)
What can I do?
This is the BluetoothService Class
public class BluetoothService {
private UUID myid = UUID.fromString("fa87c0d0-afac-11de-8a39-0800200c9a66");
private static final String appName = "myapp";
private static final int STATE_NONE = 0; // we're doing nothing
private static final int STATE_LISTEN = 1; // now listening for incoming connections
private static final int STATE_CONNECTING = 2; // now initiating an outgoing connection
private static final int STATE_CONNECTED = 3;
private static final int STATE_BUFFER_NOT_EMPTY = 4;
private String message ="";
private int mState;
private final BluetoothAdapter mBluetoothAdapter;
Context mContext;
private AcceptThread mAcceptThread;
private ConnectThread mConnectThread;
private BluetoothDevice mDevice;
private UUID deviceUUID;
private ConnectedThread mConnectedThread;
public BluetoothService(Context context) {
mContext = context;
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
mState = STATE_NONE;
}
private class AcceptThread extends Thread {
private final BluetoothServerSocket bluetoothServerSocket;
public AcceptThread(){
BluetoothServerSocket tmp = null;
try{
tmp = mBluetoothAdapter.listenUsingRfcommWithServiceRecord(appName, myid);
}catch (IOException e){
}
bluetoothServerSocket = tmp;
mState = STATE_LISTEN;
}
public void run() {
BluetoothSocket socket = null;
try {
socket = bluetoothServerSocket.accept();
} catch (IOException e) {
}
if (socket != null) {
mState = STATE_CONNECTING;
connected(socket);
}
}
public void cancel() {
try {
bluetoothServerSocket.close();
} catch (IOException e) {
}
}
}
private class ConnectThread extends Thread {
private BluetoothSocket mSocket;
public ConnectThread(BluetoothDevice device, UUID uuid) {
mDevice = device;
deviceUUID = uuid;
}
public void run(){
BluetoothSocket tmp = null;
// Get a BluetoothSocket for a connection with the
// given BluetoothDevice
try {
tmp = mDevice.createRfcommSocketToServiceRecord(deviceUUID);
} catch (IOException e) {
}
mSocket = tmp;
mBluetoothAdapter.cancelDiscovery();
try {
mSocket.connect(); //this throws exception for socket close ( but only the second time)
} catch (IOException e) {
// Close the socket
try {
mSocket.close();
} catch (IOException e1) {
}
e.printStackTrace();
}
connected(mSocket);
}
public void cancel() {
try {
mSocket.close();
} catch (IOException e) {
}
}
}
public synchronized void start() {
if (mConnectThread != null) {
mConnectThread.cancel();
mConnectThread = null;
}
if (mAcceptThread == null) {
mAcceptThread = new AcceptThread();
mAcceptThread.start();
}
}
public void startClient(BluetoothDevice device,UUID uuid){
mConnectThread = new ConnectThread(device, uuid);
mConnectThread.start();
}
private class ConnectedThread extends Thread {
private final BluetoothSocket mSocket;
private final InputStream mInStream;
private final OutputStream mOutStream;
public ConnectedThread(BluetoothSocket socket) {
mSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
try {
tmpIn = mSocket.getInputStream();
tmpOut = mSocket.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
mInStream = tmpIn;
mOutStream = tmpOut;
}
public void run(){
byte[] buffer = new byte[1024];
int bytes; // bytes returned from read()
// Keep listening to the InputStream until an exception occurs
while (true) {
// Read from the InputStream
try {
bytes = mInStream.read(buffer);
if(bytes != 0) {
String incomingMessage = new String(buffer, 0, bytes);
message = incomingMessage;
System.out.println("HO LETTO " + message);
mState = STATE_BUFFER_NOT_EMPTY;
}
} catch (IOException e) {
break;
}
}
}
//Call this from the main activity to send data to the remote device
public void write(byte[] bytes) {
try {
mOutStream.write(bytes);
} catch (IOException e) {
}
}
//termina la connessione
public void cancel() {
try {
mSocket.close();
} catch (IOException e) { }
}
}
private void connected(BluetoothSocket mSocket) {
// Start the thread to manage the connection and perform transmissions
mConnectedThread = new ConnectedThread(mSocket);
mConnectedThread.start();
mState = STATE_CONNECTED;
}
public void write(byte[] out) {
// Create temporary object
ConnectedThread r;
// Synchronize a copy of the ConnectedThread
synchronized (this) {
if (mState != STATE_CONNECTED) {
return;}
r = mConnectedThread;
}
// Perform the write unsynchronized
r.write(out);
}
public int getState(){
return mState;
}
public String getMessage(){
String tmp = null;
if(!message.equals("")){
tmp = message;
message = "";
}
mState = STATE_CONNECTED;
return tmp;
}
public void setState(int state){
this.mState = state;
}
public void cancel(){
if(mAcceptThread != null) {
mAcceptThread.cancel();
mAcceptThread = null;
}
if(mConnectThread != null) {
mConnectThread.cancel();
mConnectThread = null;
}
if(mConnectedThread != null) {
mConnectedThread.cancel();
mConnectedThread = null;
}
}
}
MainActivity
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_transition);
/* * */
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
/* * */
if(requestCode == DISCOVER_REQUEST){
if(resultCode == 120){
bluetoothService = new BluetoothService(this);
bluetoothService.start();
//after receiving some message correctly
Intent thirdActivity = new Intent(this, com.project.ThirdActivity.class);
bluetoothService.cancel();
this.startActivity(thirdActivity);
finish();
}
if(resultCode == RESULT_CANCELED){
finish();
}
}
}
}
SecondActivity the way I cancel the connection is pretty the same as MainActivity. I close the socket after some message and then start ThirdActivity
ThirdActivity
if(mode == CLIENT){
BluetoothDEvice bluetoothDevice = getIntent().getExtras().getParcelable("btdevice");
bluetoothService.startClient(bluetoothDevice,myid);
}else //SERVER
bluetoothService.start();
Possible solution:
Pass the selected MAC address from Activity2 to Activity3
In Activity3 Start the ConnectThread in the Bluetooth Service.
Use a Handler to communicate between service and the Activity3.
Make sure you close the Thread when sockets disconnect.
A brilliant example is in the following link:
https://github.com/googlesamples/android-BluetoothChat

getting device not paired after pairing in my Bluetooth app

i am building an app to display the Ecg in mobile .so i try to
establish a connection via bluetooth .but when i try to pair the
Bluetooth, the paired devices are shown. but when i try to connect, it
says device not found..i don't know how to solve the problem. Please
advise on issues in my code to connect to paired devices:Any help on
this would be greatly appreciate
this is my bluetooth.java
public class bluetooth extends Activity implements AdapterView.OnItemClickListener {
public static void disconnect(){
if (connectedThread !=null){
connectedThread.cancel();
connectedThread= null;
}
}
public static void gethandler(Handler handler){
mHandler= handler;
}
static Handler mHandler =new Handler();
static ConnectedThread connectedThread;
public static final UUID my_UUID= UUID.fromString("f53a07d4-3010-11e9-b210-d663bd873d93");
protected static final int SUCCESS_CONNECT=0;
protected static final int MESSAGE_READ=1;
ListView listView;
//ArrayAdapter is an Android SDK class for adapting an array of objects as a datasource.
// Adapters are used by Android to treat a result set uniformly whether it's from a database, file, or in-memory objects
// so that it can be displayed in a UI element.
// The ArrayAdapter is useful for the latter. Use it anywhere you would use an Adapter. E.g. attach to Android UI elements.
ArrayAdapter<String> list_adapter;
static BluetoothAdapter btAdapter;
Set<BluetoothDevice> devicesArray;
///ArrayList is an implementation of java.util.List that's backed by an array. You can use it anywhere you would use a java.util.List.
//// E.g. where you need to maintain order of a collection of objects where duplicates are allowed.
ArrayList<String> pairedDevices;
ArrayList<BluetoothDevice> devies;
IntentFilter filter;
BroadcastReceiver receiver;
#Override
protected void onCreate( Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//in Android the visual design is created in xml . And each Activity is associated to a design
//
//setContentView(R.layout.main)
//R means Resource
//
//layout means design
//
//main is the xml you have created under res->layout->main.xml
//
//Whenever you want to change your current Look of an Activity or when you move from
// one Activity to another . The other Activity must have a design to show . So we call this method in onCreate
// and this is the second statement to set the design
setContentView(R.layout.activity_bluetooth);
init();
if(btAdapter==null){
Toast.makeText(getApplicationContext(),"no bt detected", Toast.LENGTH_SHORT).show();
Log.d(TAG, "onCreate: no");
finish();
}
else{
if(!btAdapter.isEnabled()){
turnOnBT();
}
getPairedDevices();
startDiscovery();
}
}
private void getPairedDevices(){
btAdapter.cancelDiscovery();
btAdapter.startDiscovery();
}
private void turnOnBT(){
Intent intent=new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(intent,1);
}
private void startDiscovery(){
devicesArray = btAdapter.getBondedDevices();
if(devicesArray.size()>0){
for(BluetoothDevice device:devicesArray){
pairedDevices.add(device.getName());
String s="";
list_adapter.add(device.getName()+" "+s+""+"\n"+device.getAddress());
}
}
}
private void init() {
listView =(ListView)findViewById(R.id.list_item);
listView.setOnItemClickListener(this);
list_adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,0);
listView.setAdapter(list_adapter);
btAdapter = BluetoothAdapter.getDefaultAdapter();
pairedDevices =new ArrayList<String>();
filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
devies = 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);
devies.add(device); //!!!!!!!!!!
String s="";
for (int a=0;a<pairedDevices.size();a++){
if(device.getName().equals(pairedDevices.get(a))){
s="(paired)";
break;
}
}
list_adapter.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);
IntentFilter 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);
}
#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 must be enabled to continue", Toast.LENGTH_SHORT).show();
finish();
}
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if(btAdapter.isDiscovering()){
btAdapter.cancelDiscovery();
}
if(list_adapter.getItem(position).contains("(paired)")){
BluetoothDevice selectedDevice = devies.get(position);
ConnectThread connect = new ConnectThread(selectedDevice);
connect.start();
}
else{
Toast.makeText(getApplicationContext(),"device not paired", Toast.LENGTH_SHORT).show();
}
}
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 discover y because it will slow down the connection
btAdapter.cancelDiscovery();
try {
// Connect the device through the socket. This will block
// until it succeeds or throws an exception
mmSocket.connect();
//connectedThread = new ConnectedThread(mmSocket);
} 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)
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) { }
}
}
// Incoming and the outgoing strings are carried out inside this thread read is for reading incoming messages through a socket and write is for sending messages to the remote device
static 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 BluetoothSocket input and output streams
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) {
// socket not created
e.printStackTrace();
}
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
StringBuffer sbb = new StringBuffer();
public void run() {
byte[] buffer ;
int bytes;
// receiving message
while(true) {
try {
try {
sleep(30);
} catch (InterruptedException e) {
break;
}
buffer = new byte[1024];
// Read from the InputStream
bytes = mmInStream.read(buffer);
// message is in bytes form so reading them to obtain message
mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer).sendToTarget();
} catch (IOException e) {
// connection was lost and start your connection again
Log.e(TAG, "disconnected", e);
break;
}
}
}
public void write(String income) {
try {
mmOutStream.write(income.getBytes());
for (int i=0;i<income.getBytes().length;i++)
Log.v("outStream"+Integer.toString(i),Character.toString((char)(Integer.parseInt(Byte.toString(income.getBytes()[i])))));
try{
Thread.sleep(20);
}
catch (InterruptedException e1){
e1.printStackTrace();
}
} catch (IOException e1) {
e1.printStackTrace();
}
}
public void cancel(){
try {
mmSocket.close();
}
catch (IOException e){}
}
}
}
but my question is, are there any problem with mmsocket
enter image description here
i geeting like beow in my android phone.
enter image description here

bluetooth connection in android (server and client wrong)

i use these codes but Bluetooth socket never created.
i have two phones, SAMSUNG galaxy S5 and Huwaii. i run server code on Huwaii and client code in galaxy but state string in both is "waiting", that means never can create Bluetooth socket, these codes are exactly copied from GOOGLE android Tutriol and I don't know what wrong is.
myClientCode is this :
public class BluetoothActivity extends Activity implements OnItemClickListener {
protected static final int SUCCESS_CONNECT = 0;
public static final int MESSAGE_READ = 1;
TextView state;
BluetoothAdapter btadaptor;
ListView list;
ArrayAdapter<String> array;
Set<BluetoothDevice> btarray;
ArrayList<String> pairedDevices;
ArrayList<BluetoothDevice> devices;
IntentFilter filter;
BroadcastReceiver receiver;
Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
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 = "SSSSSS";
connectedThread.write(s.getBytes());
break;
case MESSAGE_READ:
byte[] readbuf = (byte[]) msg.obj;
String string = new String(readbuf);
Toast.makeText(getApplicationContext(), "sus message", 0).show();
break;
}
}
};
public static final UUID MY_UUID = UUID.fromString("0efe5656-27d7-11e6-b67b-9e71128cae77");
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
init();
if (btadaptor == null)
Toast.makeText(getApplicationContext(), "bluetooth not supported", Toast.LENGTH_SHORT).show();
else
{
if ( !btadaptor.enable())
{
startbt();
}
getPairedDevice();
startActivity();
}
}
private void startActivity() {
btadaptor.cancelDiscovery();
btadaptor.startDiscovery();
}
private void getPairedDevice() {
btarray = btadaptor.getBondedDevices();
if (btarray.size() > 0)
{
for (BluetoothDevice bt: btarray)
{
pairedDevices.add(bt.getName());
// Toast.makeText(getApplicationContext(), bt.getName(), 0).show();
}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1)
if (resultCode == RESULT_CANCELED)
{
Toast.makeText(getApplicationContext(), "you need to turn on the bluetooth to continue", Toast.LENGTH_SHORT);
finish();
}
super.onActivityResult(requestCode, resultCode, data);
}
private void init() {
state = (TextView) findViewById(R.id.textView1);
state.setText("waitingforlist");
list = (ListView) findViewById(R.id.listView);
list.setOnItemClickListener(this);
array = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
list.setAdapter(array);
btadaptor = BluetoothAdapter.getDefaultAdapter();
pairedDevices = new ArrayList<String>();
filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
devices = new ArrayList<BluetoothDevice>();
receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context contex, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action))
{
BluetoothDevice bt = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
devices.add(bt);
String s = "";
for (int a = 0; a < pairedDevices.size(); a++) {
if (bt.getName().equals(pairedDevices.get(a))) {
s = "(PAIRED)";
}
}
array.add(bt.getName() + s + "\n" + bt.getAddress());
}
}
};
registerReceiver(receiver, filter);
}
#Override
protected void onPause() {
unregisterReceiver(receiver);
super.onPause();
}
protected void startbt() {
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(intent, 1);
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
if (btadaptor.isDiscovering()) {
btadaptor.cancelDiscovery();
}
Toast.makeText(getApplicationContext(), array.getItem(arg2), 0).show();
if (array.getItem(arg2).contains("PAIRED")) {
// Toast.makeText(getApplicationContext(), "OK", 0).show();
BluetoothDevice selectedDevice = devices.get(arg2);
Toast.makeText(getApplicationContext(), selectedDevice.getAddress(), 0).show();
ConnectThread connectThread = new ConnectThread(selectedDevice);
state.setText("CreatedThread");
connectThread.start();
}
else
Toast.makeText(getApplicationContext(), "Device is not Paried", 0).show();
}
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;
state.setText(device.getName());
}
#Override
public void run() {
// Cancel discovery because it will slow down the connection
// btadaptor.cancelDiscovery();
// state.setText("DONE RUN2");
try {
// Connect the device through the socket. This will block
// until it succeeds or throws an exception
state.setText("waiting");
mmSocket.connect();
state.setText("connected");
}
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)
// manageConnectedSocket(mmSocket);
}
}
/** 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;
}
#Override
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 {
buffer = new byte[1024];
// 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) {}
}
}
}
myServerCode is this :
public class BluetoothActivity extends Activity {
protected static final int SUCCESS_CONNECT = 0;
public static final int MESSAGE_READ = 1;
Button bt;
BluetoothAdapter btadaptor;
TextView state;
Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
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 = "SSSSSS";
connectedThread.write(s.getBytes());
break;
case MESSAGE_READ:
byte[] readbuf = (byte[]) msg.obj;
String string = new String(readbuf);
Toast.makeText(getApplicationContext(), "sus message", 0).show();
break;
}
}
};
public static final UUID MY_UUID = UUID.fromString("0efe5656-27d7-11e6-b67b-9e71128cae77");
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
init();
if (btadaptor == null)
Toast.makeText(getApplicationContext(), "bluetooth not supported", Toast.LENGTH_SHORT).show();
else
{
if ( !btadaptor.enable())
{
startbt();
}
startActivity();
startDiscovering();
OnClickListener temp = new OnClickListener() {
#Override
public void onClick(View arg0) {
AcceptThread acceptThread = new AcceptThread();
state.setText("THreadCreAted");
acceptThread.start();
}
};
bt.setOnClickListener(temp);
}
}
private void startActivity() {
btadaptor.cancelDiscovery();
btadaptor.startDiscovery();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1)
if (resultCode == RESULT_CANCELED)
{
Toast.makeText(getApplicationContext(), "you need to turn on the bluetooth to continue", Toast.LENGTH_SHORT);
}
super.onActivityResult(requestCode, resultCode, data);
}
private void init() {
bt = (Button) findViewById(R.id.button1);
state = (TextView) findViewById(R.id.textView1);
state.setText("START");
btadaptor = BluetoothAdapter.getDefaultAdapter();
}
private void startDiscovering() {
Intent discoverableIntent = new
Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(discoverableIntent);
state.setText("StartDiscovering");
}
protected void startbt() {
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(intent, 1);
}
private class AcceptThread extends Thread {
private final BluetoothServerSocket mmServerSocket;
public AcceptThread() {
btadaptor.cancelDiscovery();
// Use a temporary object that is later assigned to mmServerSocket,
// because mmServerSocket is final
BluetoothServerSocket tmp = null;
try {
// MY_UUID is the app's UUID string, also used by the client code
tmp = btadaptor.listenUsingRfcommWithServiceRecord("MYAPP", MY_UUID);
}
catch (IOException e) {}
mmServerSocket = tmp;
}
#Override
public void run() {
state.setText("runStart");
BluetoothSocket socket = null;
// Keep listening until exception occurs or a socket is returned
while (true) {
try {
state.setText("WAIITING");
state.setText("WAIITING2");
socket = mmServerSocket.accept();
state.setText("ConnectionREquesRECIEVED");
}
catch (IOException e) {
break;
}
// If a connection was accepted
if (socket != null) {
state.setText("ACCEPTED");
// Do work to manage the connection (in a separate thread)
// manageConnectedSocket(socket);
try {
mmServerSocket.close();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
}
}
}
/** Will cancel the listening socket, and cause the thread to finish */
public void cancel() {
try {
mmServerSocket.close();
}
catch (IOException e) {}
}
}
private void manageConnectedSocket(BluetoothSocket mmSocket2) {
}
///////////////////////
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;
}
#Override
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 {
buffer = new byte[1024];
// 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) {}
}
}
}
is any body know whats wrong ?
or can anybody show me very simple code (both server and client) Bluetooth socket just for connection and sending message ?

Sending data from Android (Client) to Python (Server) over Bluetooth

I am trying to send data from Android Client (Nexus 4) to Python Server (Linux Machine) over Bluetooth using Python-bluez. Whenever the client writes some bytes to the OutputStream it throws an IO exception "Broken Pipe". The server also seems that it does not accept any connections although the Android client did not throw any exceptions after "socket_name.connect()"
Android Client:
public class MainActivity extends Activity {
private BluetoothSocket ClientSocket;
private BluetoothDevice Client;
private ConnectedThread Writer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public BluetoothAdapter mblue;
public void connect(View sender)
{
mblue = BluetoothAdapter.getDefaultAdapter();
int REQUEST_ENABLE_BT = 1;
final TextView er = (TextView)findViewById(R.id.Error);
if(mblue == null)
er.setText("No Bluetooth!");
else if (mblue.isEnabled()) {
er.setText(mblue.getAddress() + " " + mblue.getName());
}
else{
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
}
public void disov(View sender)
{
final TextView er = (TextView)findViewById(R.id.Error);
boolean tr = mblue.startDiscovery();
if(tr == true)
{
er.setText("Disovering !!");
}
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter);
}
public void start(View sender)
{
final TextView er = (TextView)findViewById(R.id.Error);
final TextView lol = (TextView)findViewById(R.id.editText1);
Writer.write(lol.getText().toString().getBytes());
lol.setText("");
}
public void send(View sender)
{
ConnectThread con = new ConnectThread(Client);
con.start();
}
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent)
{
String action = intent.getAction();
// When discovery finds a device
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// Add the name and address to an array adapter to show in a ListView
//mArrayAdapter.add(device.getName() + "\n" + device.getAddress());
final TextView er = (TextView)findViewById(R.id.Error);
if(device.getAddress().equals("9C:2A:70:49:61:B0") == true)
{
Client = device;
er.setText("Connected with the target device!");
}
}
}
};
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;
UUID myuuid = UUID.fromString("94f39d29-7d6d-437d-973b-fba39e49d4ee");
final TextView er = (TextView)findViewById(R.id.Error);
// 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(myuuid);
} catch (IOException e) {}
ClientSocket = mmSocket = tmp;
Writer = new ConnectedThread(ClientSocket);
}
public void run() {
// Cancel discovery because it will slow down the connection
mblue.cancelDiscovery();
final TextView er = (TextView)findViewById(R.id.Error);
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) {}
return;
}
// Do work to manage the connection (in a separate thread)
//manageConnectedSocket(mmSocket);
}
/** Will cancel an in-progress connection, and close the socket */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) {}
}
}
public 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;
final TextView er = (TextView)findViewById(R.id.Error);
// 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;
er.setText(er.getText() + "\n" + socket.toString());
}
public void run() {
byte[] buffer = new byte[1024]; // 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) {
final TextView er = (TextView)findViewById(R.id.Error);
try {
mmOutStream.write(bytes);
//mmOutStream.
} catch (IOException e)
{
er.setText(e.toString());
}
}
/* Call this from the main activity to shutdown the connection */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}
}
}
Python Server:
from bluetooth import *
server_sock=BluetoothSocket( RFCOMM )
server_sock.bind(("",PORT_ANY))
server_sock.listen(1)
port = server_sock.getsockname()[1]
uuid = "94f39d29-7d6d-437d-973b-fba39e49d4ee"
advertise_service( server_sock, "SampleServer",
service_id = uuid,
service_classes = [ uuid, SERIAL_PORT_CLASS ],
profiles = [ SERIAL_PORT_PROFILE ],
# protocols = [ OBEX_UUID ]
)
print("Waiting for connection on RFCOMM channel %d" % port)
client_sock, client_info = server_sock.accept()
print("Accepted connection from ", client_info)
try:
while True:
data = client_sock.recv(1024)
if len(data) == 0: break
print("received [%s]" % data)
except IOError:
pass
print("disconnected")
client_sock.close()
server_sock.close()
print("all done")
Any help is appreciated.
You have used two public classes i.e public class MainActivity extends Activity{} and public class ConnectedThread extends Thread {}. But in Java there should be one public class and any number of other classes in one JavaClass file. So remove public class ConnectedThread extends Thread {} from that file and create a new Java class: public class ConnectedThread extends Thread {} in the same package.

Why is my app closing after bluetooth printer printed the text?

I watched in debugger but i can't see what's the problem.
public class MainActivity extends Activity implements OnItemClickListener{
public BluetoothAdapter BtAdaptor;
public ArrayAdapter<String> listAdaptor;
public ArrayList<String> PairedDevices;
public ArrayList<BluetoothDevice> devices;
public ListView Lista;
public Set<BluetoothDevice> DevicesArray;
public IntentFilter filter;
public BroadcastReceiver receiver;
public static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
protected static final int SUCCES_CONNECT = 0;
public static final int MESSAGE_READ = 1;
public static final int MESSAGE_PRINTED = 2;
public Handler mHandler;
public InputStream mmInStream;
public OutputStream mmOutStream;
public ConnectedThread connectedThread;
public BluetoothDevice selectedDevice;
public BluetoothSocket mmSocket;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button scaneaza = (Button)findViewById(R.id.btnScan);
Button printeaza = (Button)findViewById(R.id.btnSend);
printeaza.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
ConnectThread connect = new ConnectThread(selectedDevice);
connect.start();
}
});
scaneaza.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// Lista.setAdapter(listAdaptor);
startDiscovery();
if(devices.size()!=0){
listAdaptor.clear();
listAdaptor.notifyDataSetChanged();
}
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);
listAdaptor.add(device.getName()+" \n "+device);
devices.add(device);
}
else if(BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)){
Toast.makeText(getApplicationContext(), "S-a terminat cautarea!", Toast.LENGTH_SHORT).show();
}
}
};
registerReceiver(receiver, filter);
IntentFilter filter2 = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(receiver, filter2);
}
});
BtAdaptor = BluetoothAdapter.getDefaultAdapter();
initiere();
if(BtAdaptor == null){
Toast.makeText(getApplicationContext(), "Dispozitivul nu are Bt", 0).show();
}
else {
if(!BtAdaptor.isEnabled()){
Intent PornesteBt = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
Intent DescoperaBt = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
startActivityForResult(PornesteBt,1);
DescoperaBt.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 120);
startActivity(DescoperaBt);
startDiscovery();
}
else {}
}
mHandler = new Handler(){
#Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch(msg.what){
case SUCCES_CONNECT:
connectedThread = new ConnectedThread((BluetoothSocket)msg.obj);
Toast.makeText(getApplicationContext(), "Connected", Toast.LENGTH_SHORT).show();
String s="\n Mesaj trimis pt a testa.";
connectedThread.write(s.getBytes());
break;
case MESSAGE_PRINTED:
connectedThread = new ConnectedThread((BluetoothSocket)msg.obj);
connectedThread.cancel();
break;
}
}
};
}
private void startDiscovery() {
BtAdaptor.cancelDiscovery();
BtAdaptor.startDiscovery();
}
private void initiere() {
ListView Lista = (ListView)findViewById(R.id.lView);
Lista.setOnItemClickListener(this);
listAdaptor = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,0);
Lista.setAdapter(listAdaptor);
PairedDevices = new ArrayList<String>();
filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
devices = new ArrayList<BluetoothDevice>();
}
#Override
protected void onDestroy() {
super.onPause();
unregisterReceiver(receiver);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
if(BtAdaptor.isDiscovering()){
BtAdaptor.cancelDiscovery();
}
Toast.makeText(getApplicationContext(), "device selectat", 0).show();
// Object[] o= DevicesArray.toArray();
// BluetoothDevice selectedDevice = (BluetoothDevice)o[arg2];
selectedDevice = devices.get(arg2);
}
I used ConnectThread activity from http://developer.android.com/guide/topics/connectivity/bluetooth.html
private class ConnectThread extends Thread {
// public 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
mmSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) { }
// mmSocket = tmp;
}
public void run() {
// Cancel discovery because it will slow down the connection
BtAdaptor.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) { }
return;
}
// Do work to manage the connection (in a separate thread)
// manageConnectedSocket(mmSocket);
mHandler.obtainMessage(SUCCES_CONNECT,mmSocket).sendToTarget();
}
/** Will cancel an in-progress connection, and close the socket */
public void cancel() {
Toast.makeText(getApplicationContext(), "A intrat in cancel ", Toast.LENGTH_SHORT).show();
if(mmSocket != null){
try {
mmSocket.close();
} catch (IOException e) { }
}
}
}
And ConnectedThread...
private class ConnectedThread extends Thread {
// private final BluetoothSocket mmSocket;
public ConnectedThread(BluetoothSocket socket) {
mmSocket = socket;
// InputStream tmpIn;
// OutputStream tmpOut;
try {
// tmpIn = socket.getInputStream();
mmInStream = socket.getInputStream();
// tmpOut = socket.getOutputStream();
mmOutStream = 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 {
buffer = new byte[1024];
// 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 {
mHandler.obtainMessage(MESSAGE_PRINTED).sendToTarget();
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 want to connect only as a client. Thanks.

Categories

Resources