getting device not paired after pairing in my Bluetooth app - android

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

Related

Send String via bluetooth OnClick()

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

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 ?

binding a android bluetooth server to a socket

Android 4.04(java) server to ubuntu 12.04(python) client with bluetooth (RFCOMM)
I'm currently trying to get a bluetooth communication between and android 4.04 galaxy taplet and linux computer with python (the computer will be running a ROS robot, and I need the tablet for GPS and INS data). I need the taplet to function as a server. Both drivers support RFCOMM, but the python option connects based on "Address" and "Port" where the java android connects on "UUID".
I'm currently looking for a way to give my android server a static port number, but I'm also open for other ways to solve the problem.
I have been stuck here for quite a while and have found lots of simular issues but none which solved my case, hope you guys can help me out.
Question: how can I bind my android bluetooth server to a socket ?
Ps: forgive that the code android code isen't perfect it have been modified quite a few times looking for workarounds
My current android code:
public class MainActivity extends Activity{
ArrayAdapter<String> listadapter;
ListView listView;
BluetoothAdapter mBluetoothAdapter;
Set<BluetoothDevice> devicesArray;
ArrayList<String> pairedDevices;
BroadcastReceiver receiver;
AcceptThread acceptThread;
public static final UUID MY_UUID = UUID.fromString("94f39d29-7d6d-437d-973b-fba39e49d4ee");
protected static final int SUCCESS_CONNECT = 0;
protected static final int MESSAGE_READ = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
init();
acceptThread = new AcceptThread();
acceptThread.start();
if(mBluetoothAdapter == null){
Toast.makeText(getApplicationContext(), "No bluetooth detected", 0).show();
finish();
}
else{
if(!mBluetoothAdapter.isEnabled()){
turnOnBluetooth();
}
getPairedDevices();
startDiscorevy();
}
}
private void startDiscorevy() {
mBluetoothAdapter.cancelDiscovery();
mBluetoothAdapter.startDiscovery();
}
private void turnOnBluetooth() {
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(intent, 1);
}
private void getPairedDevices() {
devicesArray = mBluetoothAdapter.getBondedDevices();
if(devicesArray.size()>0){
for(BluetoothDevice device:devicesArray){
pairedDevices.add(device.getName()+"\n"+device.getAddress());
}
}
}
private void init(){
Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 600);
startActivity(discoverableIntent);
listView = (ListView) findViewById(R.id.listView);
listadapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,0);
listView.setAdapter(listadapter);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
pairedDevices = new ArrayList<String>();
}
#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 enable to continue", 0).show();
finish();
}
}
#Override
protected void onPause() {
super.onPause();
acceptThread.cancel();
}
private class AcceptThread extends Thread {
private final BluetoothServerSocket mmServerSocket;
public AcceptThread() {
BluetoothServerSocket tmp = null;
try {
tmp = mBluetoothAdapter.listenUsingInsecureRfcommWithServiceRecord("Location_Service", MY_UUID);
} catch (IOException e) { }
mmServerSocket = tmp;
}
public void run() {
BluetoothSocket socket = null;
while (true) {
try {
socket = mmServerSocket.accept();
} catch (IOException e) {
break;
}
if (socket != null) {
manageConnectedSocket(socket);
try {
mmServerSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
break;
}
}
}
private void manageConnectedSocket(BluetoothSocket socket) {
OutputStream mmOutStream;
BluetoothSocket mmSocket;
mmSocket = socket;
OutputStream tmpOut = null;
try {
tmpOut = mmSocket.getOutputStream();
} catch (IOException e) { }
mmOutStream = tmpOut;
byte[] bytes = null;
String toSend = "hello world";
bytes = toSend.getBytes();
try {
mmOutStream.write(bytes);
} catch (IOException e) { }
try {
mmSocket.close();
} catch (IOException e) { }
}
public void cancel() {
try {
mmServerSocket.close();
} catch (IOException e) { }
}
}
}
My current python code:
#!python
import bluetooth
from bluetooth import *
import sys
bluetooth_name = "GT-P5110"
bluetooth_address = None
uuid = None
print "looking for device"
nearby_devices = bluetooth.discover_devices()
for bdaddr in nearby_devices:
if bluetooth_name == bluetooth.lookup_name( bdaddr):
bluetooth_address == bdaddr
print "device found on address:"
print bdaddr
service_matches = find_service(uuid = uuid, address = bluetooth_address)
first_match = service_matches[0]
port = first_match["port"]
name = first_match["name"]
host = first_match["host"]
print " --- "
print port
print name
print host
print " --- "
sock = bluetooth.BluetoothSocket( bluetooth.RFCOMM)
sock.connect((bluetooth_address, port))
sock.close()
Note that the python code finds the device in both searches, returns its address correctly, and concludes the port and name to be none. I then get an error in sock.connect(addr,port) since port carnt be none.

how to know android device version or API via bluetooth

hi everyone,
In my application i want to send data only 2.3.3 and above android deceives but when i start discover Bluetooth devices my application get all activated devices .
Those devices are both android and other devices.How can i filter or know about devices who have 2.3.3 or above version
my code give below:
public class MainActivity extends Activity implements OnItemClickListener {
Button mBtnConnect;
ListView mlist;
BluetoothAdapter mBluetoothAdapter;
IntentFilter filter;
MyBluetoothAdapter blu_adapter=null;
Set<BluetoothDevice> deviceArray;
ArrayList<String> pairedDevices;
ArrayList<String> pairedDevices_list;
ArrayList<String> bonded_list;
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;
Handler mHandler=new Handler() {
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (SUCCESS_CONNECT) {
case SUCCESS_CONNECT:
ConnectedThread connecteThread=new ConnectedThread((BluetoothSocket)msg.obj);
Toast.makeText(getApplicationContext(), "Connected", 0).show();
String s="successfully connected ";
connecteThread.write(s.getBytes());
break;
case MESSAGE_READ:
byte[] readBuf=(byte[]) msg.obj;
String string =new String(readBuf);
Toast.makeText(getApplicationContext(), string, 0).show();
break;
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initilizeField();
if (mBluetoothAdapter == null) {
Toast.makeText(getApplicationContext(),
"No bluetooth device found", 0).show();
finish();
}
else {
if (!mBluetoothAdapter.isEnabled()) {
TurnonBT();
}
getPairedDevices();
StartDiscovery();
}
mBtnConnect.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
blu_adapter=new MyBluetoothAdapter(MainActivity.this, pairedDevices,bonded_list);
mlist.setAdapter(blu_adapter);
}
});
}
private void StartDiscovery() {
// TODO Auto-generated method stub
mBluetoothAdapter.cancelDiscovery();
mBluetoothAdapter.startDiscovery();
}
private void TurnonBT() {
// TODO Auto-generated method stub
Intent enableBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBluetooth, 1);
}
private void initilizeField() {
// TODO Auto-generated method stub
mlist = (ListView) findViewById(R.id.listView);
mBtnConnect = (Button) findViewById(R.id.mBtnConnect);
mlist = (ListView) findViewById(R.id.listView);
pairedDevices = new ArrayList<String>();
pairedDevices_list = new ArrayList<String>();
bonded_list=new ArrayList<String>();
Devices=new ArrayList<BluetoothDevice>();
/*listAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, 0);
mlist.setAdapter(listAdapter);*/
//click listner
mlist.setOnItemClickListener(this);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 400);
startActivity(discoverableIntent);
Toast.makeText(getApplicationContext(), "Now your device is discoverable by others", Toast.LENGTH_LONG).show();
filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
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);
// deviceArray=new
}
BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
Devices.add(device);
//- listAdapter.add(device.getName() + " "+s+" "+"\n"+ device.getAddress());
for (BluetoothDevice devicePaired : Devices) {
if(bonded_list.contains(devicePaired)){
}
else{
bonded_list.add("Not Paired");
}
}
if(pairedDevices.contains(device.getName())){
}
else{
pairedDevices.add(device.getName());
}
} else if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
/* if(listAdapter.getCount()>0){
for(int i=0;i<listAdapter.getCount();i++){
for(int a=0;a<pairedDevices.size();a++){
if(listAdapter.getItem(i).equals(pairedDevices.get(a))){
}
}
}
}*/
} else if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {
if(mBluetoothAdapter.getState()==mBluetoothAdapter.STATE_OFF){
TurnonBT();
}
}
}
};
private void getPairedDevices() {
// TODO Auto-generated method stub
deviceArray = mBluetoothAdapter.getBondedDevices();
if (deviceArray.size() > 0) {
for (BluetoothDevice device : deviceArray) {
if(pairedDevices.contains(device.getName())){
//device already in paired array list
}
else{
pairedDevices.add(device.getName());
bonded_list.add("Paired");
}
}
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_CANCELED) {
Toast.makeText(getApplicationContext(),
"Bluetooth must be enable to connect", Toast.LENGTH_SHORT)
.show();
finish();
}
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
getPairedDevices();
StartDiscovery();
/*filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
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);*/
//unregisterReceiver(receiver);
}
#Override
protected void onDestroy() {
super.onDestroy();
if (mBluetoothAdapter != null) {
mBluetoothAdapter.cancelDiscovery();
}
unregisterReceiver(receiver);
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
// TODO Auto-generated method stub
if(mBluetoothAdapter.isDiscovering()){
mBluetoothAdapter.cancelDiscovery();
}
if(bonded_list.get(position).contains("Paired")){
//Toast.makeText(getApplicationContext(), "This device is already paired", 0).show();
//Object[] o=deviceArray.toArray();
BluetoothDevice selectedDevices=Devices.get(position);
ConnectThread connect=new ConnectThread(selectedDevices);
connect.start();
}
else{
Toast.makeText(getApplicationContext(), "This device is Not paired", 0).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 discovery because it will slow down the connection
mBluetoothAdapter.cancelDiscovery();
try {
// Connect the device through the socket. This will block
// until it succeeds or throws an exception
mmSocket.connect();
} catch (IOException connectException) {
// Unable to connect; close the socket and get out
try {
mmSocket.close();
} catch (IOException closeException) { }
return;
}
// Do work to manage the connection (in a separate thread)
// manageConnectedSocket(mmSocket);
mHandler.obtainMessage(SUCCESS_CONNECT,mmSocket).sendToTarget();
}
private void manageConnectedSocket(BluetoothSocket mmSocket2) {
// TODO Auto-generated method stub
}
/** 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) { }
}
}
}
int currentapiVersion = android.os.Build.VERSION.SDK_INT;
if (currentapiVersion >= android.os.Build.VERSION_CODES.FROYO){
// Do something for froyo and above versions
} else{
// do something for phones running an SDK before froyo
}

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