I want to discover bluetooth devices in range, list and pair to them on click. I used following code but its just closing application when I click on device name which I want to pair.
I want to know mistake in my code or any other way to do what i need.
package com.marakana;
import java.util.Set;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
public class BluetoothDemo extends Activity {
// Debugging
private static final String TAG = "DeviceListActivity";
private static final boolean D = true;
// Return Intent extra
public static String EXTRA_DEVICE_ADDRESS = "device_address";
// Member fields
private BluetoothAdapter mBtAdapter;
private ArrayAdapter<String> mPairedDevicesArrayAdapter;
private ArrayAdapter<String> mNewDevicesArrayAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Setup the window
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.device_list);
// Set result CANCELED incase the user backs out
setResult(Activity.RESULT_CANCELED);
// Initialize the button to perform device discovery
Button scanButton = (Button) findViewById(R.id.button_scan);
scanButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
doDiscovery();
v.setVisibility(View.GONE);
}
});
// Initialize array adapters. One for already paired devices and
// one for newly discovered devices
mPairedDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.device_name);
mNewDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.device_name);
// Find and set up the ListView for paired devices
ListView pairedListView = (ListView) findViewById(R.id.paired_devices);
pairedListView.setAdapter(mPairedDevicesArrayAdapter);
pairedListView.setOnItemClickListener(mDeviceClickListener);
// Find and set up the ListView for newly discovered devices
ListView newDevicesListView = (ListView) findViewById(R.id.new_devices);
newDevicesListView.setAdapter(mNewDevicesArrayAdapter);
newDevicesListView.setOnItemClickListener(mDeviceClickListener);
// Register for broadcasts when a device is discovered
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
this.registerReceiver(mReceiver, filter);
// Register for broadcasts when discovery has finished
filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
this.registerReceiver(mReceiver, filter);
// Get the local Bluetooth adapter
mBtAdapter = BluetoothAdapter.getDefaultAdapter();
// Get a set of currently paired devices
Set<BluetoothDevice> pairedDevices = mBtAdapter.getBondedDevices();
// If there are paired devices, add each one to the ArrayAdapter
if (pairedDevices.size() > 0) {
findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE);
for (BluetoothDevice device : pairedDevices) {
mPairedDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
}
} else {
String noDevices = getResources().getText(R.string.none_paired).toString();
mPairedDevicesArrayAdapter.add(noDevices);
}
}
#Override
protected void onDestroy() {
super.onDestroy();
// Make sure we're not doing discovery anymore
if (mBtAdapter != null) {
mBtAdapter.cancelDiscovery();
}
// Unregister broadcast listeners
this.unregisterReceiver(mReceiver);
}
/**
* Start device discover with the BluetoothAdapter
*/
private void doDiscovery() {
if (D) Log.d(TAG, "doDiscovery()");
// Indicate scanning in the title
setProgressBarIndeterminateVisibility(true);
setTitle(R.string.scanning);
// Turn on sub-title for new devices
findViewById(R.id.title_new_devices).setVisibility(View.VISIBLE);
// If we're already discovering, stop it
if (mBtAdapter.isDiscovering()) {
mBtAdapter.cancelDiscovery();
}
// Request discover from BluetoothAdapter
mBtAdapter.startDiscovery();
}
// The on-click listener for all devices in the ListViews
private OnItemClickListener mDeviceClickListener = new OnItemClickListener() {
public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3) {
// Cancel discovery because it's costly and we're about to connect
mBtAdapter.cancelDiscovery();
// Get the device MAC address, which is the last 17 chars in the View
String info = ((TextView) v).getText().toString();
String address = info.substring(info.length() - 17);
// Create the result Intent and include the MAC address
Intent intent = new Intent();
intent.putExtra(EXTRA_DEVICE_ADDRESS, address);
// Set result and finish this Activity
setResult(Activity.RESULT_OK, intent);
finish();
}
};
// The BroadcastReceiver that listens for discovered devices and
// changes the title when discovery is finished
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
#Override
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);
// If it's already paired, skip it, because it's been listed already
if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
}
// When discovery is finished, change the Activity title
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
setProgressBarIndeterminateVisibility(false);
setTitle(R.string.select_device);
if (mNewDevicesArrayAdapter.getCount() == 0) {
String noDevices = getResources().getText(R.string.none_found).toString();
mNewDevicesArrayAdapter.add(noDevices);
}
}
}
};
}
In my first answer the logic is shown for those who want to go with the logic only.
I think I was not able to make clear to #chalukya3545, that's why I am adding the whole code to let him know the exact flow of the code.
BluetoothDemo.java
public class BluetoothDemo extends Activity {
ListView listViewPaired;
ListView listViewDetected;
ArrayList<String> arrayListpaired;
Button buttonSearch,buttonOn,buttonDesc,buttonOff;
ArrayAdapter<String> adapter,detectedAdapter;
static HandleSeacrh handleSeacrh;
BluetoothDevice bdDevice;
BluetoothClass bdClass;
ArrayList<BluetoothDevice> arrayListPairedBluetoothDevices;
private ButtonClicked clicked;
ListItemClickedonPaired listItemClickedonPaired;
BluetoothAdapter bluetoothAdapter = null;
ArrayList<BluetoothDevice> arrayListBluetoothDevices = null;
ListItemClicked listItemClicked;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
listViewDetected = (ListView) findViewById(R.id.listViewDetected);
listViewPaired = (ListView) findViewById(R.id.listViewPaired);
buttonSearch = (Button) findViewById(R.id.buttonSearch);
buttonOn = (Button) findViewById(R.id.buttonOn);
buttonDesc = (Button) findViewById(R.id.buttonDesc);
buttonOff = (Button) findViewById(R.id.buttonOff);
arrayListpaired = new ArrayList<String>();
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
clicked = new ButtonClicked();
handleSeacrh = new HandleSeacrh();
arrayListPairedBluetoothDevices = new ArrayList<BluetoothDevice>();
/*
* the above declaration is just for getting the paired bluetooth devices;
* this helps in the removing the bond between paired devices.
*/
listItemClickedonPaired = new ListItemClickedonPaired();
arrayListBluetoothDevices = new ArrayList<BluetoothDevice>();
adapter= new ArrayAdapter<String>(BluetoothDemo.this, android.R.layout.simple_list_item_1, arrayListpaired);
detectedAdapter = new ArrayAdapter<String>(BluetoothDemo.this, android.R.layout.simple_list_item_single_choice);
listViewDetected.setAdapter(detectedAdapter);
listItemClicked = new ListItemClicked();
detectedAdapter.notifyDataSetChanged();
listViewPaired.setAdapter(adapter);
}
#Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
getPairedDevices();
buttonOn.setOnClickListener(clicked);
buttonSearch.setOnClickListener(clicked);
buttonDesc.setOnClickListener(clicked);
buttonOff.setOnClickListener(clicked);
listViewDetected.setOnItemClickListener(listItemClicked);
listViewPaired.setOnItemClickListener(listItemClickedonPaired);
}
private void getPairedDevices() {
Set<BluetoothDevice> pairedDevice = bluetoothAdapter.getBondedDevices();
if(pairedDevice.size()>0)
{
for(BluetoothDevice device : pairedDevice)
{
arrayListpaired.add(device.getName()+"\n"+device.getAddress());
arrayListPairedBluetoothDevices.add(device);
}
}
adapter.notifyDataSetChanged();
}
class ListItemClicked implements OnItemClickListener
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
bdDevice = arrayListBluetoothDevices.get(position);
//bdClass = arrayListBluetoothDevices.get(position);
Log.i("Log", "The dvice : "+bdDevice.toString());
/*
* here below we can do pairing without calling the callthread(), we can directly call the
* connect(). but for the safer side we must usethe threading object.
*/
//callThread();
//connect(bdDevice);
Boolean isBonded = false;
try {
isBonded = createBond(bdDevice);
if(isBonded)
{
//arrayListpaired.add(bdDevice.getName()+"\n"+bdDevice.getAddress());
//adapter.notifyDataSetChanged();
getPairedDevices();
adapter.notifyDataSetChanged();
}
} catch (Exception e) {
e.printStackTrace();
}//connect(bdDevice);
Log.i("Log", "The bond is created: "+isBonded);
}
}
class ListItemClickedonPaired implements OnItemClickListener
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
bdDevice = arrayListPairedBluetoothDevices.get(position);
try {
Boolean removeBonding = removeBond(bdDevice);
if(removeBonding)
{
arrayListpaired.remove(position);
adapter.notifyDataSetChanged();
}
Log.i("Log", "Removed"+removeBonding);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/*private void callThread() {
new Thread(){
public void run() {
Boolean isBonded = false;
try {
isBonded = createBond(bdDevice);
if(isBonded)
{
arrayListpaired.add(bdDevice.getName()+"\n"+bdDevice.getAddress());
adapter.notifyDataSetChanged();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}//connect(bdDevice);
Log.i("Log", "The bond is created: "+isBonded);
}
}.start();
}*/
private Boolean connect(BluetoothDevice bdDevice) {
Boolean bool = false;
try {
Log.i("Log", "service method is called ");
Class cl = Class.forName("android.bluetooth.BluetoothDevice");
Class[] par = {};
Method method = cl.getMethod("createBond", par);
Object[] args = {};
bool = (Boolean) method.invoke(bdDevice);//, args);// this invoke creates the detected devices paired.
//Log.i("Log", "This is: "+bool.booleanValue());
//Log.i("Log", "devicesss: "+bdDevice.getName());
} catch (Exception e) {
Log.i("Log", "Inside catch of serviceFromDevice Method");
e.printStackTrace();
}
return bool.booleanValue();
};
public boolean removeBond(BluetoothDevice btDevice)
throws Exception
{
Class btClass = Class.forName("android.bluetooth.BluetoothDevice");
Method removeBondMethod = btClass.getMethod("removeBond");
Boolean returnValue = (Boolean) removeBondMethod.invoke(btDevice);
return returnValue.booleanValue();
}
public boolean createBond(BluetoothDevice btDevice)
throws Exception
{
Class class1 = Class.forName("android.bluetooth.BluetoothDevice");
Method createBondMethod = class1.getMethod("createBond");
Boolean returnValue = (Boolean) createBondMethod.invoke(btDevice);
return returnValue.booleanValue();
}
class ButtonClicked implements OnClickListener
{
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.buttonOn:
onBluetooth();
break;
case R.id.buttonSearch:
arrayListBluetoothDevices.clear();
startSearching();
break;
case R.id.buttonDesc:
makeDiscoverable();
break;
case R.id.buttonOff:
offBluetooth();
break;
default:
break;
}
}
}
private BroadcastReceiver myReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Message msg = Message.obtain();
String action = intent.getAction();
if(BluetoothDevice.ACTION_FOUND.equals(action)){
Toast.makeText(context, "ACTION_FOUND", Toast.LENGTH_SHORT).show();
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
try
{
//device.getClass().getMethod("setPairingConfirmation", boolean.class).invoke(device, true);
//device.getClass().getMethod("cancelPairingUserInput", boolean.class).invoke(device);
}
catch (Exception e) {
Log.i("Log", "Inside the exception: ");
e.printStackTrace();
}
if(arrayListBluetoothDevices.size()<1) // this checks if the size of bluetooth device is 0,then add the
{ // device to the arraylist.
detectedAdapter.add(device.getName()+"\n"+device.getAddress());
arrayListBluetoothDevices.add(device);
detectedAdapter.notifyDataSetChanged();
}
else
{
boolean flag = true; // flag to indicate that particular device is already in the arlist or not
for(int i = 0; i<arrayListBluetoothDevices.size();i++)
{
if(device.getAddress().equals(arrayListBluetoothDevices.get(i).getAddress()))
{
flag = false;
}
}
if(flag == true)
{
detectedAdapter.add(device.getName()+"\n"+device.getAddress());
arrayListBluetoothDevices.add(device);
detectedAdapter.notifyDataSetChanged();
}
}
}
}
};
private void startSearching() {
Log.i("Log", "in the start searching method");
IntentFilter intentFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
BluetoothDemo.this.registerReceiver(myReceiver, intentFilter);
bluetoothAdapter.startDiscovery();
}
private void onBluetooth() {
if(!bluetoothAdapter.isEnabled())
{
bluetoothAdapter.enable();
Log.i("Log", "Bluetooth is Enabled");
}
}
private void offBluetooth() {
if(bluetoothAdapter.isEnabled())
{
bluetoothAdapter.disable();
}
}
private void makeDiscoverable() {
Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(discoverableIntent);
Log.i("Log", "Discoverable ");
}
class HandleSeacrh extends Handler
{
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case 111:
break;
default:
break;
}
}
}
}
Here is the main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button
android:id="#+id/buttonOn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="On"/>
<Button
android:id="#+id/buttonDesc"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Make Discoverable"/>
<Button
android:id="#+id/buttonSearch"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Search"/>
<Button
android:id="#+id/buttonOff"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Bluetooth Off"/>
<ListView
android:id="#+id/listViewPaired"
android:layout_width="match_parent"
android:layout_height="120dp">
</ListView>
<ListView
android:id="#+id/listViewDetected"
android:layout_width="match_parent"
android:layout_height="match_parent">
</ListView>
</LinearLayout>
Add this permissions to your AndroidManifest.xml file:
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
The output for this code will look like this.
The Best way is do not use any pairing code.
Instead of onClick go to other function or other class where You create the socket using UUID.
Android automatically pops up for pairing if already not paired.
or see this link for better understanding
Below is code for the same:
private OnItemClickListener mDeviceClickListener = new OnItemClickListener() {
public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3) {
// Cancel discovery because it's costly and we're about to connect
mBtAdapter.cancelDiscovery();
// Get the device MAC address, which is the last 17 chars in the View
String info = ((TextView) v).getText().toString();
String address = info.substring(info.length() - 17);
// Create the result Intent and include the MAC address
Intent intent = new Intent();
intent.putExtra(EXTRA_DEVICE_ADDRESS, address);
// Set result and finish this Activity
setResult(Activity.RESULT_OK, intent);
// **add this 2 line code**
Intent myIntent = new Intent(view.getContext(), Connect.class);
startActivityForResult(myIntent, 0);
finish();
}
};
Connect.java file is :
public class Connect extends Activity {
private static final String TAG = "zeoconnect";
private ByteBuffer localByteBuffer;
private InputStream in;
byte[] arrayOfByte = new byte[4096];
int bytes;
public BluetoothDevice mDevice;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.connect);
try {
setup();
} catch (ZeoMessageException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ZeoMessageParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void setup() throws ZeoMessageException, ZeoMessageParseException {
// TODO Auto-generated method stub
getApplicationContext().registerReceiver(receiver,
new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED));
getApplicationContext().registerReceiver(receiver,
new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECTED));
BluetoothDevice zee = BluetoothAdapter.getDefaultAdapter().
getRemoteDevice("**:**:**:**:**:**");// add device mac adress
try {
sock = zee.createRfcommSocketToServiceRecord(
UUID.fromString("*******************")); // use unique UUID
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Log.d(TAG, "++++ Connecting");
try {
sock.connect();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Log.d(TAG, "++++ Connected");
try {
in = sock.getInputStream();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Log.d(TAG, "++++ Listening...");
while (true) {
try {
bytes = in.read(arrayOfByte);
Log.d(TAG, "++++ Read "+ bytes +" bytes");
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Log.d(TAG, "++++ Done: test()");
}}
private static final LogBroadcastReceiver receiver = new LogBroadcastReceiver();
public static class LogBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context paramAnonymousContext, Intent paramAnonymousIntent) {
Log.d("ZeoReceiver", paramAnonymousIntent.toString());
Bundle extras = paramAnonymousIntent.getExtras();
for (String k : extras.keySet()) {
Log.d("ZeoReceiver", " Extra: "+ extras.get(k).toString());
}
}
};
private BluetoothSocket sock;
#Override
public void onDestroy() {
getApplicationContext().unregisterReceiver(receiver);
if (sock != null) {
try {
sock.close();
} catch (IOException e) {
e.printStackTrace();
}
}
super.onDestroy();
}
}
if you have the BluetoothDevice object you can create bond(pair) from api 19 onwards with bluetoothDevice.createBond() method.
Edit
for callback, if the request was accepted or denied you will have to create a BroadcastReceiver with BluetoothDevice.ACTION_BOND_STATE_CHANGED action
Edit: I have just explained logic to pair here. If anybody want to go with the complete code then see my another answer. I have answered here for logic only but I was not able to explain properly, So I have added another answer in the same thread.
Try this to do pairing:
If you are able to search the devices then this would be your next step
ArrayList<BluetoothDevice> arrayListBluetoothDevices = NEW ArrayList<BluetoothDevice>;
I am assuming that you have the list of Bluetooth devices added in the arrayListBluetoothDevices:
BluetoothDevice bdDevice;
bdDevice = arrayListBluetoothDevices.get(PASS_THE_POSITION_TO_GET_THE_BLUETOOTH_DEVICE);
Boolean isBonded = false;
try {
isBonded = createBond(bdDevice);
if(isBonded)
{
Log.i("Log","Paired");
}
} catch (Exception e)
{
e.printStackTrace();
}
The createBond() method:
public boolean createBond(BluetoothDevice btDevice)
throws Exception
{
Class class1 = Class.forName("android.bluetooth.BluetoothDevice");
Method createBondMethod = class1.getMethod("createBond");
Boolean returnValue = (Boolean) createBondMethod.invoke(btDevice);
return returnValue.booleanValue();
}
Add this line into your Receiver in the ACTION_FOUND
if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
arrayListBluetoothDevices.add(device);
}
Related
I'm developing an Android app that is a kind of a remote control (that works via bluetooth) for one Arduino device. I've already could pair my phone with remote Bluetooth. Also it seems that I could establish connection which I've checked with an ACTION_ACL_CONNECTED state like this:
private final BroadcastReceiver connectedReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
showToast("Conneeeeeeeeeeeeected");
}
}
};
The problem is when I press a button on my app to send some data to the remote Bluetooth, nothing happens (a LED must change its state from OFF to ON). Could you please check what's wrong, maybe it's something with my ConnectThread? Here is my code:
public class MainActivity extends AppCompatActivity {
private final static UUID MY_UUID = UUID.fromString("ecff8f1a-ac66-11e6-80f5-76304dec7eb7");
BluetoothSocket mmSocket;
Button whiteBtn; // after clicking this button, data from my phone are send to remote bluetooth
whiteBtn = (Button) findViewById(R.id.white_btn);
whiteBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
whiteBtnOn();
}
});
#Override
protected void onCreate(Bundle savedInstanceState) {
// Get Bluetooth Adapter
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
showToast("Bluetooth is not supported on this device");
}
// Enable Bluetooth
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
mPairedDevicesArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, arrListPaired);
pairedListView.setAdapter(mPairedDevicesArrayAdapter);
// Find out which devices have been already paired
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
if (pairedDevices.size() > 0) {
showToast("Paired devices have been found");
// Loop through the paired devices
for (BluetoothDevice device : pairedDevices) {
arrListPaired.add(device.getName() + '\n' + device.getAddress());
mPairedDevicesArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, arrListPaired);
}
pairedListView.setAdapter(mPairedDevicesArrayAdapter);
}
// Click event for items from paired devices list (Possible actions: “Connect”, which establishes connection between my phone and remote Bluetooth, “Unpair”, “Cancel”)
pairedListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, final View view, final int position, long id) {
final String info = ((TextView) view).getText().toString();
int address = info.indexOf(":");
final String adr = info.substring(address - 2, info.length());
final int positionToRemove = position;
final AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setMessage("What should we do?");
//builder.setMessage("Unpair this device?");
builder.setPositiveButton("Unpair", new OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(adr);
// UNPAIR DEVICES
unpair(device);
arrListPaired.remove(positionToRemove);
mPairedDevicesArrayAdapter.notifyDataSetChanged();
// END UNPAIR DEVICES
}
});
builder.setNeutralButton("Cancel", new OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
});
// Establish Connection between devices
builder.setNegativeButton("Connect", new OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
showToast("Establish connection");
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(adr);
ConnectThread ct = new ConnectThread(device);
ct.start();
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);
registerReceiver(connectedReceiver, filter);
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
});
#Override
protected void onPause() {
if (mBluetoothAdapter != null) {
if (mBluetoothAdapter.isDiscovering()) {
mBluetoothAdapter.cancelDiscovery();
}
}
super.onPause();
}
#Override
protected void onDestroy() {
unregisterReceiver(mReceiver);
super.onDestroy();
}
private void showToast(String message) {
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
}
private void pairDevice(BluetoothDevice device) {
try {
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
registerReceiver(receiver, filter);
Method method = device.getClass().getMethod("createBond", (Class[]) null);
method.invoke(device, (Object[]) null);
} catch (Exception e) {
e.printStackTrace();
}
}
private void unpair(BluetoothDevice device) {
showToast("Unpaired button is clicked");
try {
if(mmSocket!=null) {mmSocket.close();}
Method m = device.getClass().getMethod("removeBond", (Class[]) null);
m.invoke(device, (Object[]) null);
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
// Connecting threat
private class ConnectThread extends Thread {
private final BluetoothDevice mmDevice;
public ConnectThread(BluetoothDevice device) {
BluetoothSocket tmp = null;
mmDevice = device;
try {
tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) {}
mmSocket = tmp;
}
public void run () {
mBluetoothAdapter.cancelDiscovery();
try {
mmSocket.connect();
} catch (IOException connectException) {
try {
mmSocket.close();
} catch (IOException closeException) {}
return;
}
//manageConnectedSocket(mmSocket);
}
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) {}
}
}
// Managing a connection
// Broadcast receiver for connected device
private final BroadcastReceiver connectedReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
showToast("Conneeeeeeeeeeeeected");
}
}
};
// Send data after clicking on a button
private void whiteBtnOn() {
if (mmSocket != null) {
showToast("White btn is clicked");
try {
mmSocket.getOutputStream().write("TO".toString().getBytes());
}
catch (IOException e) {}
}
}
}
}
Thanks in advance for your suggestions!
Try use UUID for Bluetooth SPP:
private final static UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");
instead of:
private final static UUID MY_UUID = UUID.fromString("ecff8f1a-ac66-11e6-80f5-76304dec7eb7");
I'm trying to make an application that is using bluetooth.It's very simple but I'm stuck at connecting devices.
So far I've made 2 listviews, one is displaying paired devices and the other found devices.I dont understand how sockets work and how to make the device server or a client.
Can someone please explain me that or at least tell me what to do with the code I already made(copied).
I've gone through all the tutorials I could find and I still dont understand it.The bluetooth chat example is very confusing, I'm a beginner in android programming and didn't really study much java.
This is the code:
public class ConnectThread extends Thread{
BluetoothDevice device;
private BluetoothSocket socket;
ConnectThread(){
connect(device, MY_UUID);
}
public boolean connect(BluetoothDevice bTDevice, UUID mUUID) {
BluetoothSocket temp = null;
try {
temp = bTDevice.createRfcommSocketToServiceRecord(mUUID);
} catch (IOException e) {
Log.d("CONNECTTHREAD","Could not create RFCOMM socket:" + e.toString());
return false;
}
try {
socket.connect();
} catch(IOException e) {
Log.d("CONNECTTHREAD","Could not connect: " + e.toString());
try {
socket.close();
} catch(IOException close) {
Log.d("CONNECTTHREAD", "Could not close connection:" + e.toString());
return false;
}
}
return true;
}
public boolean cancel() {
try {
socket.close();
} catch(IOException e) {
Log.d("CONNECTTHREAD","Could not close connection:" + e.toString());
return false;
}
return true;
}
}
private class AcceptThread extends Thread {
private final BluetoothServerSocket mmServerSocket;
public AcceptThread() {
// 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 = bluetooth.listenUsingRfcommWithServiceRecord(NAME, MY_UUID);
} catch (IOException e) { }
mmServerSocket = tmp;
}
public void run() {
BluetoothSocket socket = null;
// Keep listening until exception occurs or a socket is returned
while (true) {
try {
socket = mmServerSocket.accept();
} catch (IOException e) {
break;
}
// If a connection was accepted
if (socket != null) {
// Do work to manage the connection (in a separate thread)
try {
mmServerSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
break;
}
}
}
/** Will cancel the listening socket, and cause the thread to finish */
public void cancel() {
try {
mmServerSocket.close();
} catch (IOException e) { }
}}
This is the xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:orientation="horizontal"
android:layout_weight="1"
android:baselineAligned="false">
<ListView
android:layout_width="170dp"
android:layout_height="fill_parent"
android:layout_gravity="start"
android:background="#drawable/lviewbg"
android:id="#+id/paired_devies">
</ListView>
<ListView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="fill_horizontal"
android:background="#drawable/lviewbg"
android:id="#+id/new_devices">
</ListView>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="50dp">
<Button
android:id="#+id/discover"
android:layout_width="0dp"
android:layout_height="50dp"
android:layout_weight="1"
android:background="#aa0000ff"
android:text="#string/disc"
style="?android:attr/buttonBarButtonStyle"
/>
<Button
android:layout_width="0dp"
android:layout_height="50dp"
android:layout_weight="1"
android:background="#aa0000ff"
android:text="#string/discoverable"
android:onClick="makeDiscoverable"
style="?android:attr/buttonBarButtonStyle"
/>
</LinearLayout>
</LinearLayout>
This is rest of the code if you need it:
package com.example.user.broj;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.util.Set;
import java.util.UUID;
public class BluetoothDevices extends AppCompatActivity{
private static final String TAG = "DeviceListActivity";
private static final boolean D = true;
BluetoothDevice device;
static int REQUEST_ENABLE_BT = 1;
static int DISCOVERABLE_BT_REQUEST_CODE = 1;
static int DISCOVERABLE_DURATION = 120;
public static String EXTRA_DEVICE_ADDRESS = "device_address";
private BluetoothAdapter bluetooth = BluetoothAdapter.getDefaultAdapter();
ArrayAdapter<String> mPairedDevicesArrayAdapter;
private ArrayAdapter<String> mNewDevicesArrayAdapter;
//This is used for connecting devices
static final String NAME = "BluetoothGame";
static final UUID MY_UUID = UUID.fromString("ae19c8fa-9b60-11e5-8994-feff819cdc9f");
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.start);
Button scanButton = (Button) findViewById(R.id.discover);
scanButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
doDiscovery();
view.setClickable(false);
}
});
//enabling bluetooth
if(!bluetooth.isEnabled()){
Intent btIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(btIntent, REQUEST_ENABLE_BT);
}
//arrayadapters for paired and new devices list views
mPairedDevicesArrayAdapter = new ArrayAdapter<>(this, R.layout.device_name);
mNewDevicesArrayAdapter = new ArrayAdapter<>(this, R.layout.device_name);
//listview for paired devices
ListView deviceList = (ListView) findViewById(R.id.paired_devies);
deviceList.setAdapter(mPairedDevicesArrayAdapter);
deviceList.setOnItemClickListener(mDeviceClickListener);
//listview for new devices
ListView newDevicesListView = (ListView) findViewById(R.id.new_devices);
newDevicesListView.setAdapter(mNewDevicesArrayAdapter);
newDevicesListView.setOnItemClickListener(mDeviceClickListener);
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
this.registerReceiver(mReceiver, filter);
filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
this.registerReceiver(mReceiver, filter);
bluetooth = BluetoothAdapter.getDefaultAdapter();
Set<BluetoothDevice> pairedDevices = bluetooth.getBondedDevices();
if (pairedDevices.size() > 0) {
//findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE);
for (BluetoothDevice device : pairedDevices) {
mPairedDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
}
} else {
String noDevices = getResources().getText(R.string.none_paired).toString();
mPairedDevicesArrayAdapter.add(noDevices);
}
}
//button onClick for making the device discoverable
public void makeDiscoverable(View view) {
Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, DISCOVERABLE_DURATION);
startActivityForResult(discoverableIntent, DISCOVERABLE_BT_REQUEST_CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == DISCOVERABLE_BT_REQUEST_CODE){
if (resultCode == DISCOVERABLE_DURATION){
Toast.makeText(getApplicationContext(), "Your device is now discoverable by other devices for " +
DISCOVERABLE_DURATION + " seconds",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Fail to enable discoverability on your device.",
Toast.LENGTH_SHORT).show();
}
}
}
#Override
protected void onDestroy() {
super.onDestroy();
// Make sure we're not doing discovery anymore
if (bluetooth != null) {
bluetooth.cancelDiscovery();
}
// Unregister broadcast listeners
this.unregisterReceiver(mReceiver);
}
private void doDiscovery() {
if (D) Log.d(TAG, "doDiscovery()");
// Indicate scanning in the title
setProgressBarIndeterminateVisibility(true);
setTitle(R.string.scanning);
// Turn on sub-title for new devices
// findViewById(R.id.title_new_devices).setVisibility(View.VISIBLE);
// If we're already discovering, stop it
if (bluetooth.isDiscovering()) {
bluetooth.cancelDiscovery();
}
// Request discover from BluetoothAdapter
bluetooth.startDiscovery();
}
private AdapterView.OnItemClickListener mDeviceClickListener = new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3) {
// Cancel discovery because it's costly and we're about to connect
bluetooth.cancelDiscovery();
// Get the device MAC address, which is the last 17 chars in the View
String info = ((TextView) v).getText().toString();
String address = info.substring(info.length() - 17);
// Create the result Intent and include the MAC address
Intent intent = new Intent();
intent.putExtra(EXTRA_DEVICE_ADDRESS, address);
// Set result and finish this Activity
setResult(Activity.RESULT_OK, intent);
finish();
}
};
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Button scanButton = (Button) findViewById(R.id.discover);
String action = intent.getAction();
// When discovery finds a device
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// If it's already paired, skip it, because it's been listed already
if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
}
// When discovery is finished, change the Activity title
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
setProgressBarIndeterminateVisibility(false);
setTitle(R.string.select_device);
scanButton.setClickable(true);
if (mNewDevicesArrayAdapter.getCount() == 0) {
String noDevices = getResources().getText(R.string.none_found).toString();
mNewDevicesArrayAdapter.add(noDevices);
}
}
}
};
}
Async class for connection via Bluetoothsocket
UUID SERIAL_UUID = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");
InputStream is1;
OutputStream os1;
BluetoothAdapter bluetoothAdapter = null;
BluetoothSocket socket = null;
class UserInterface extends Thread {
BluetoothDevice bdDevice;
public UserInterface() {
bdDevice = your pair device;
}
#Override
public void run() {
Looper.prepare();
try {
BluetoothDevice device = bluetoothAdapter.getRemoteDevice(bdDevice.getAddress());
if (socket != null && socket.isConnected()) {
is1.close();
os1.close();
socket.close();
}
try {
socket = device.createInsecureRfcommSocketToServiceRecord(SERIAL_UUID);
} catch (Exception e) {
Log.e("", "Error creating socket");
}
if (bluetoothAdapter.isDiscovering()) {
bluetoothAdapter.cancelDiscovery();
}
try {
socket.connect();
Log.e("", "Connected Rfcomm");
} catch (IOException e) {
Log.e("", e.getMessage());
try {
Log.e("", "trying fallback...");
socket = device.createInsecureRfcommSocketToServiceRecord(SERIAL_UUID);
socket.connect();
Log.e("", "Connected serial UDID");
} catch (Exception e2) {
Log.e("", "Couldn't establish Bluetooth connection!");
}
}
if (socket.isConnected()) {
// dismiss Progress Dialog
os1 = socket.getOutputStream();
is1 = socket.getInputStream();
Log.i("TAG", "Socket Connected");
//code after socket connect
} else {
// dismiss Progress Dialog
showProgressDialogToast("Please restart bluetooth Device");
closeSocket();
Log.i("TAG", "Socket Disconnected");
}
Log.i("Log", "Removed" + bdDevice.getName());
} catch (Exception e) {
// TODO Auto-generated catch block
Log.i("Log", "Under Catch of thread");
e.printStackTrace();
// dismiss Progress Dialog
}
}
}
use Thread class like this
UserInterface userInterface = new UserInterface();
userInterface.start();
Basically refer the tutorial given by android developers on their site.
In every connectivity there should be one server and one client. The server will just run the accept thread and the client will run the connect thread. Once the accept thread started, you need to connect from the client side with the proper device name.
hi guys i am trying to send string from one phone to anther .
1) from one phone(client) i am clicking the paired listview to connect with the anther device(ConnectThread).
2) the second phone which is the server alerts that he has been connected with the device in step 1(AcceptThread).
3) after he get connected he start a new managerconnection thread and send along a string(in AcceptThread after connecting is sucessfull it starts a new managerConnection thread .
4) the other phone(after been connected to server it starts a new managerConnecting thread) should get the bytes from function read and put in the log how much bytes he read it seems its not getting any bytes at all can someone tell me what should i changed in my code?
package com.example.barhom.waves;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.os.Bundle;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Set;
import java.util.UUID;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class BlueToothServerActivity extends Activity {
private static final int REQUEST_ENABLE_BT = 1;
private static final String TAG = "buckysmessage";
private Button onBtn;
private Button offBtn;
private Button listBtn;
private Button findBtn;
private TextView text;
private TextView serverStatus;
private BluetoothAdapter myBluetoothAdapter;
private Set<BluetoothDevice> pairedDevices;
private ListView myListView;
private ArrayAdapter<String> BTArrayAdapter;
private AcceptThread mSecureAcceptThread;
private manageConnectedSocket manager ;
// Unique UUID for this application
private static final UUID MY_UUID =
UUID.fromString("fa87c0d0-afac-11de-8a39-0800200c9a66");
private static final String NAME_SECURE = "waves";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.bluetooth_server);
serverStatus = (TextView) findViewById(R.id.serverStatus);
// take an instance of BluetoothAdapter - Bluetooth radio
myBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if(myBluetoothAdapter == null) {
onBtn.setEnabled(false);
offBtn.setEnabled(false);
listBtn.setEnabled(false);
findBtn.setEnabled(false);
text.setText("Status: not supported");
Toast.makeText(getApplicationContext(),"Your device does not support Bluetooth",
Toast.LENGTH_LONG).show();
} else {
text = (TextView) findViewById(R.id.text);
onBtn = (Button)findViewById(R.id.turnOn);
onBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
on(v);
}
});
offBtn = (Button)findViewById(R.id.turnOff);
offBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
off(v);
}
});
listBtn = (Button)findViewById(R.id.paired);
listBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
list(v);
}
});
findBtn = (Button)findViewById(R.id.search);
findBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
find(v);
}
});
myListView = (ListView)findViewById(R.id.listView1);
// create the arrayAdapter that contains the BTDevices, and set it to the ListView
BTArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
myListView.setAdapter(BTArrayAdapter);
myListView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> adapter, View v, int position,
long arg3)
{
String value = (String)adapter.getItemAtPosition(position);
Toast.makeText(getApplicationContext(),"Listview clicked" ,
Toast.LENGTH_LONG).show();
// assuming string and if you want to get the value on click of list item
// do what you intend to do on click of listview row
}
});
}
}
#Override
protected void onResume() {
super.onResume();
// setting the device to listen for connections(bluetooth)
AcceptThread mSecureAcceptThread= new AcceptThread();
mSecureAcceptThread.start();
}
public void on(View view){
if (!myBluetoothAdapter.isEnabled()) {
Intent turnOnIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(turnOnIntent, REQUEST_ENABLE_BT);
Toast.makeText(getApplicationContext(),"Bluetooth turned on" ,
Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(getApplicationContext(),"Bluetooth is already on",
Toast.LENGTH_LONG).show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
if(requestCode == REQUEST_ENABLE_BT){
if(myBluetoothAdapter.isEnabled()) {
text.setText("Status: Enabled");
} else {
text.setText("Status: Disabled");
}
}
}
public void list(View view){
// get paired devices
pairedDevices = myBluetoothAdapter.getBondedDevices();
// put it's one to the adapter
for(BluetoothDevice device : pairedDevices)
BTArrayAdapter.add(device.getName()+ "\n" + device.getAddress());
Toast.makeText(getApplicationContext(),"Show Paired Devices",
Toast.LENGTH_SHORT).show();
}
final BroadcastReceiver bReceiver = 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 the MAC address of the object to the arrayAdapter
BTArrayAdapter.add(device.getName() + "\n" + device.getAddress());
BTArrayAdapter.notifyDataSetChanged();
}
}
};
public void find(View view) {
if (myBluetoothAdapter.isDiscovering()) {
// the button is pressed when it discovers, so cancel the discovery
myBluetoothAdapter.cancelDiscovery();
}
else {
BTArrayAdapter.clear();
myBluetoothAdapter.startDiscovery();
registerReceiver(bReceiver, new IntentFilter(BluetoothDevice.ACTION_FOUND));
}
}
public void off(View view){
myBluetoothAdapter.disable();
text.setText("Status: Disconnected");
Toast.makeText(getApplicationContext(),"Bluetooth turned off",
Toast.LENGTH_LONG).show();
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
unregisterReceiver(bReceiver);
}
private class AcceptThread extends Thread {
private final BluetoothServerSocket mmServerSocket;
private boolean running = true;
public AcceptThread() {
// Use a temporary object that is later assigned to mmServerSocket,
// because mmServerSocket is final
serverStatus.setText("Server Status: Listing for connection");
Log.d(TAG, "SERVER IS LISING FOR CONNECTIONS");
BluetoothServerSocket tmp = null;
try {
// MY_UUID is the app's UUID string, also used by the client code
tmp = myBluetoothAdapter.listenUsingRfcommWithServiceRecord(NAME_SECURE, MY_UUID);
} catch (IOException e) {running = false; }
mmServerSocket = tmp;
}
public void run() {
BluetoothSocket socket = null;
// Keep listening until exception occurs or a socket is returned
while (running) {
try {
socket = mmServerSocket.accept();
} catch (IOException e) {
break;
}
// If a connection was accepted
if (socket != null) {
// Do work to manage the connection (in a separate thread)
manager=new manageConnectedSocket(socket);
manager.start();
try {
mmServerSocket.close();
Log.d(TAG, "SERVER IS CONNECTED");
String blahblah="asdasds";
manager.write(blahblah.getBytes());
break;
}catch (IOException e) {
break;
}
}
}
}
/** Will cancel the listening socket, and cause the thread to finish */
public void cancel() {
try {
mmServerSocket.close();
} catch (IOException e) { }
}
}
private class manageConnectedSocket extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public manageConnectedSocket(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[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
} 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);
Log.d(TAG,"WROTE A STRING TO ANTHER PHONE");
} catch (IOException e) { }
}
/* Call this from the main activity to shutdown the connection */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}
}
}
and the code for the client(the second phone):
package com.example.barhom.waves;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Set;
import java.util.UUID;
public class BlueToothClientActivity extends AppCompatActivity {
private static final int REQUEST_ENABLE_BT = 1;
private static final String TAG = "buckysmessage";
private Button onBtn;
private Button offBtn;
private Button listBtn;
private Button findBtn;
private TextView text;
private TextView serverStatus;
private ConnectThread mConnectThread;
private BluetoothAdapter myBluetoothAdapter;
private Set<BluetoothDevice> pairedDevices;
private ListView myListView;
private ArrayAdapter<String> BTArrayAdapter;
private manageConnectedSocket manager ;
// Unique UUID for this application
private static final UUID MY_UUID =
UUID.fromString("fa87c0d0-afac-11de-8a39-0800200c9a66");
private static final String NAME_SECURE = "waves";
private BluetoothDevice device;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.bluetooth_client);
serverStatus = (TextView) findViewById(R.id.serverStatus);
// take an instance of BluetoothAdapter - Bluetooth radio
myBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if(myBluetoothAdapter == null) {
onBtn.setEnabled(false);
offBtn.setEnabled(false);
listBtn.setEnabled(false);
findBtn.setEnabled(false);
text.setText("Status: not supported");
Toast.makeText(getApplicationContext(), "Your device does not support Bluetooth",
Toast.LENGTH_LONG).show();
} else {
text = (TextView) findViewById(R.id.text);
onBtn = (Button)findViewById(R.id.turnOn);
onBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
on(v);
}
});
offBtn = (Button)findViewById(R.id.turnOff);
offBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
off(v);
}
});
listBtn = (Button)findViewById(R.id.paired);
listBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
list(v);
}
});
findBtn = (Button)findViewById(R.id.search);
findBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
find(v);
}
});
myListView = (ListView)findViewById(R.id.listView1);
// create the arrayAdapter that contains the BTDevices, and set it to the ListView
BTArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
myListView.setAdapter(BTArrayAdapter);
myListView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> adapter, View v, int position,
long arg3)
{
String info = ((TextView) v).getText().toString();
String address = info.substring(info.length() - 17);
Toast.makeText(getApplicationContext(),"adress is"+address,
Toast.LENGTH_LONG).show();
device = myBluetoothAdapter.getRemoteDevice(address);
ConnectThread mConnectThread=new ConnectThread(device );
mConnectThread.start();
// assuming string and if you want to get the value on click of list item
// do what you intend to do on click of listview row
}
});
}
}
#Override
protected void onResume() {
super.onResume();
}
public void on(View view){
if (!myBluetoothAdapter.isEnabled()) {
Intent turnOnIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(turnOnIntent, REQUEST_ENABLE_BT);
Toast.makeText(getApplicationContext(),"Bluetooth turned on" ,
Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(getApplicationContext(),"Bluetooth is already on",
Toast.LENGTH_LONG).show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
if(requestCode == REQUEST_ENABLE_BT){
if(myBluetoothAdapter.isEnabled()) {
text.setText("Status: Enabled");
} else {
text.setText("Status: Disabled");
}
}
}
public void list(View view){
// get paired devices
pairedDevices = myBluetoothAdapter.getBondedDevices();
// put it's one to the adapter
for(BluetoothDevice device : pairedDevices)
BTArrayAdapter.add(device.getName()+ "\n" + device.getAddress());
Toast.makeText(getApplicationContext(),"Show Paired Devices",
Toast.LENGTH_SHORT).show();
}
final BroadcastReceiver bReceiver = 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 the MAC address of the object to the arrayAdapter
BTArrayAdapter.add(device.getName() + "\n" + device.getAddress());
BTArrayAdapter.notifyDataSetChanged();
}
}
};
public void find(View view) {
if (myBluetoothAdapter.isDiscovering()) {
// the button is pressed when it discovers, so cancel the discovery
myBluetoothAdapter.cancelDiscovery();
}
else {
BTArrayAdapter.clear();
myBluetoothAdapter.startDiscovery();
registerReceiver(bReceiver, new IntentFilter(BluetoothDevice.ACTION_FOUND));
}
}
public void off(View view){
myBluetoothAdapter.disable();
text.setText("Status: Disconnected");
Toast.makeText(getApplicationContext(), "Bluetooth turned off",
Toast.LENGTH_LONG).show();
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
unregisterReceiver(bReceiver);
}
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
myBluetoothAdapter.cancelDiscovery();
try {
// Connect the device through the socket. This will block
// until it succeeds or throws an exception
mmSocket.connect();
manager=new manageConnectedSocket(mmSocket);
manager.start();
} 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 manageConnectedSocket extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public manageConnectedSocket(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[1024]; // buffer store for the stream
// Keep listening to the InputStream until an exception occurs
while (true) {
try {
int read = -1;
final byte[] bytes = new byte[2048];
for (; (read = mmInStream.read(bytes)) > -1;) {
final int count = read;
Log.d(TAG,"String size is"+count);
}
} 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) { }
}
}
}
any help will be great!
thanks.
i'm trying to connect (over a onclick method of a listview where all available bluetooth devices are listed) to a bluetooth device in my Class Bluetooth. That class starts the intentservice BluetoothService, where i create a BluetoothSocket and connect to the Device.
After the Connection works i would like to go to my MainActivity, while my Connection is on and there I want to send Bluetooth-Messages. But the BluetoothConnection always disconnects ...
BLUETOOTH.JAVA
public class Bluetooth extends ActionBarActivity {
ArrayList arrayList1;
ListView lv;
ArrayAdapter<String> arrayAdapter;
MainActivity ma = new MainActivity();
BroadcastReceiver mReceiver;
static final String TAG = "Bluetooth";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.popup);
Intent intent = getIntent();
arrayList1=intent.getStringArrayListExtra("values");
lv= (ListView) findViewById(R.id.listView);
getSurroundingDevicesandConnect();
}
#Override
protected void onStart(){
super.onStart();
}
public void getSurroundingDevicesandConnect() {
setContentView(R.layout.popup);
ma.bluetooth.startDiscovery();
if (ma.bluetooth.startDiscovery()) {
System.out.println("discovery started");
mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
arrayAdapter.add(device.getName() + "\n" + device.getAddress());
System.out.println("while onreceive" + arrayList1);
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
Log.v(TAG, "Entered the Finished ");
ma.bluetooth.cancelDiscovery();
} else {
System.out.println("hoppala da funktioniert was nciht");
}
}
};
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter);
System.out.println("wurde registriert...");
}
setListView();
}
public void setListView() {
lv = (ListView) findViewById(R.id.listView);
arrayAdapter = new ArrayAdapter<String>(
this,
android.R.layout.select_dialog_item,
arrayList1
);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
// TODO Auto-generated method stub
String devicehelper = arrayList1.get(position).toString();
String[] device = devicehelper.split("\n");
String deviceName = device[0];
String deviceMAC = device[1];
//TODO: das hier muss in service..
Intent serviceIntent = new Intent();
serviceIntent.setAction("jritter.stamer.bluetoothtest.BluetoothService");
serviceIntent.putExtra("deviceMAC", deviceMAC);
BluetoothService bts = new BluetoothService();
bts.onHandleIntent(serviceIntent);
// boolean connected = connectWithDeviceNow(deviceMAC);
// if (connected) {
// System.out.println("Connected!");
// Toast.makeText(getApplicationContext(), "Connected", Toast.LENGTH_LONG).show();
// } else {
// System.out.println("Connection Failure");
// Toast.makeText(getApplicationContext(), "Connection Failure", Toast.LENGTH_LONG).show();
// }
// //onRestart();
// Toast.makeText(getApplicationContext(), "Mit Gerät " + deviceName + " verbunden", Toast.LENGTH_LONG);
}
});
lv.setAdapter(arrayAdapter);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.bluetooth, menu);
return true;
}
public void onDestroy(){
super.onDestroy();
unregisterReceiver(mReceiver);
}
}
BLUETOOTHSERVICE.JAVA
public class BluetoothService extends IntentService {
MainActivity ma = new MainActivity();
BluetoothSocket btSocket = null;
ConnectedThread mConnectedThread;
public BluetoothService() {
super("BluetoothService");
}
#Override
protected void onHandleIntent(Intent intent) {
String MAC = intent.getStringExtra("deviceMAC");
// create device and set the MAC address
BluetoothDevice device = ma.bluetooth.getRemoteDevice(MAC);//mydeviceaddress
System.out.println("devicename: " + device + device.getName());
ma.bluetooth.cancelDiscovery();
try {
btSocket = ma.createBluetoothSocket(device);
} catch (IOException e) {
System.out.println("socket creation failed");
}
// Establish the Bluetooth socket connection.
try {
btSocket.connect();
System.out.println("mit geraet verbunden");
} catch (IOException e) {
System.out.println("geraet nicht in eichweite");
try {
btSocket.close();
} catch (IOException e2) {
System.out.println("Socket closing doesnt work!");
}
}
mConnectedThread = new ConnectedThread(btSocket);
mConnectedThread.setPriority(Thread.MAX_PRIORITY);
mConnectedThread.start();
}
}
MAINACTIVITY.JAVA
public class MainActivity extends ActionBarActivity {
BluetoothAdapter bluetooth = BluetoothAdapter.getDefaultAdapter();
static final boolean D = true;
static final int REQUEST_ENABLE_BT = 2;
static final String TAG = "Bluetooth";
// String for MAC address
static String mydeviceaddress;
// SPP UUID service - this should work for most devices
static final UUID BTMODULEUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
VerticalSeekBar Master, Channel1, Channel2, Channel3, Channel4, Channel5, Channel6, FX1, FX2, FX3, FX4;
CheckBox MuteMaster, Mute1, Mute2, Mute3, Mute4, Mute5, Mute6;
Button connect;
TextView textView;
ArrayList arrayList;
Spinner effects;
List<String> spinnerArray = new ArrayList<String>(Arrays.asList("no effect", "Hall A", "Hall B"));
VerticalSeekBar vsb;
private static long back_pressed;
//BroadcastReceiver mReceiver;
Intent intent;
//BluetoothService btservice;
ConnectedThread mConnectedThread;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initializeVariables();
deviceSupportBluetooth();//?
turnBluetoothOn();
intent = getIntent();
}
#Override
public synchronized void onResume() {
super.onResume();
if (D) Log.e(TAG, "+ ON RESUME +");
effectsConfig(effects);
connect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//do something...
//connect bluetooth activity
sendMessage(v);
}
});
seekbarConfig(Master, "Master");
seekbarConfig(Channel1, "Channel1");
seekbarConfig(Channel2, "Channel2");
seekbarConfig(Channel3, "Channel3");
seekbarConfig(Channel4, "Channel4");
seekbarConfig(Channel5, "Channel5");
seekbarConfig(Channel6, "Channel6");
muteConfig(MuteMaster);
muteConfig(Mute1);
muteConfig(Mute2);
muteConfig(Mute3);
muteConfig(Mute4);
muteConfig(Mute5);
muteConfig(Mute6);
}
//TODO: MCONNECTEDTHREAD
public void sendMessage(View view) {
Intent intent = new Intent(this, Bluetooth.class);
intent.putExtra("values", arrayList);
startActivity(intent);
}
private void initializeVariables() {
Master = (VerticalSeekBar) findViewById(R.id.Seekbar);
Channel1 = (VerticalSeekBar) findViewById(R.id.Seekbar1);
Channel2 = (VerticalSeekBar) findViewById(R.id.seekbar2);
Channel3 = (VerticalSeekBar) findViewById(R.id.seekbar3);
Channel4 = (VerticalSeekBar) findViewById(R.id.seekbar4);
Channel5 = (VerticalSeekBar) findViewById(R.id.seekbar5);
Channel6 = (VerticalSeekBar) findViewById(R.id.seekbar6);
vsb = (VerticalSeekBar) findViewById(R.id.impulse2);
textView = (TextView) findViewById(R.id.textView);
MuteMaster = (CheckBox) findViewById(R.id.muteMaster);
Mute1 = (CheckBox) findViewById(R.id.mute1);
Mute2 = (CheckBox) findViewById(R.id.mute2);
Mute3 = (CheckBox) findViewById(R.id.mute3);
Mute4 = (CheckBox) findViewById(R.id.mute4);
Mute5 = (CheckBox) findViewById(R.id.mute5);
Mute6 = (CheckBox) findViewById(R.id.mute6);
connect = (Button) findViewById(R.id.connect);
effects = (Spinner) findViewById(R.id.spinner2);
arrayList = new ArrayList();
}
//android...
#Override
public void onStart() {
super.onStart();
if (D) Log.e(TAG, "++ ON START ++");
}
#Override
public void onDestroy() {
super.onDestroy();
if (D) Log.e(TAG, "++ ON DESTROY ++");
}
protected void onStop() {
Log.w(TAG, "App stopped");
super.onStop();
}
public void onBackPressed(){
onResume();
if (back_pressed + 2000 > System.currentTimeMillis()) super.onBackPressed();
else Toast.makeText(getBaseContext(), "Press once again to exit!", Toast.LENGTH_SHORT).show();
back_pressed = System.currentTimeMillis();
}
#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 boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onConfigurationChanged(Configuration newConfig)
{
super.onConfigurationChanged(newConfig);
}
// TODO GUI...
public void effectsConfig(Spinner spinner){
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
this, android.R.layout.simple_spinner_item, spinnerArray);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
Spinners abc = new Spinners();
abc.setSpinner(spinner);
abc.setmConnectedThread(mConnectedThread);
spinner.setOnItemSelectedListener(abc);
}
public void muteConfig(CheckBox mute){
Checkboxes abc = new Checkboxes();
abc.setmConnectedThread(mConnectedThread);
mute.setOnClickListener(abc);
}
public void seekbarConfig(VerticalSeekBar seekBar, final String fadername) {
Seekbars abc = new Seekbars();
abc.setFadername(fadername);
abc.setmConnectedThread(mConnectedThread);
seekBar.setOnSeekBarChangeListener(abc);
}
// TODO Bluetooth handling...
public BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException {
return device.createInsecureRfcommSocketToServiceRecord(BTMODULEUUID);
//creates secure outgoing connecetion with BT device using UUID
}
public void deviceSupportBluetooth() {
if (bluetooth == null) {
Toast.makeText(this, "Your Device does not support Bluetooth", Toast.LENGTH_LONG).show();
finish();
return;
}
}
public void turnBluetoothOn() {
if (!bluetooth.isEnabled()) {
Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
// Otherwise, setup the control session
}
}
}
CONNECTEDTHREAD.JAVA
class ConnectedThread extends Thread {
MainActivity ma = new MainActivity();
private final InputStream mmInStream;
private final OutputStream mmOutStream;
final int handlerState = 0; //used to identify handler message
Handler bluetoothIn;
//creation of the connect thread
public ConnectedThread(BluetoothSocket socket) {
InputStream tmpIn = null;
OutputStream tmpOut = null;
try {
//Create I/O streams for connection
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) {
}
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
byte[] buffer = new byte[256];
int bytes;
// Keep looping to listen for received messages
while (true) {
try {
bytes = mmInStream.read(buffer); //read bytes from input buffer
String readMessage = new String(buffer, 0, bytes);
// Send the obtained bytes to the UI Activity via handler
bluetoothIn.obtainMessage(handlerState, bytes, -1, readMessage).sendToTarget();
} catch (IOException e) {
break;
}
}
}
//write method
public void write(String input) {
byte[] msgBuffer = input.getBytes(); //converts entered String into bytes
try {
mmOutStream.write(msgBuffer); //write bytes over BT connection via outstream
} catch (IOException e) {
//if you cannot write, close the application
Toast.makeText(ma.getBaseContext(), "Connection Failure", Toast.LENGTH_LONG).show();
ma.finish();
}
}
}
You don't want to use IntentService for this. An IntentService shuts itself down when it has no more work to do. This means that as soon as you return from onHandleIntent() your service will shut down. Just extend Service and move the code you have in onHandleIntent() to onStartCommand(). Make sure that you return START_STICKY from onHandleIntent() and make sure that you have code that stops your Service when you are done with it.
The next problem is that in several classes you do this:
MainActivity ma = new MainActivity();
This is bad. You cannot instantiate Android components using new. Only the Android framework can instantiate Android components (Service, Activity, BroadcastReceiver, ContentProvider), because the framework needs to set up the correct Context. If you need to call methods in an Activity, you will either need to have a reference to the (Android created) Activity, or you need to make the methods static.
Your code is a mess :-( You should manage all the bluetooth stuff in your Service, not distribute the logic partly in the Service and partly in an Activity. Your classes are all interdependent. This is bad design and is causing you problems. You need to create a clear and clean interface between your Service and your Activity.
Look in your logcat to see what nasty exceptions are being thrown. That is most likely the cause of your "bluetooth disconnect"
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
}