I am designing this app for api level 2.2
I want pair with a available bluetooth device and then listen the ststus,
I have done that by the following way:
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
if(btAdapter.isDiscovering()){
btAdapter.cancelDiscovery();
}
if(!listAdapter.getItem(i).contains("Paired")){
try {
BluetoothDevice selectedDevice = devices.get(i);
pairDevice(selectedDevice);
Intent intent=new Intent(getBaseContext(),ConnectedBtActivity.class);
intent.putExtra("MAC",selectedDevice.getAddress());
startActivity(intent);
}
catch (Exception e){}
}
else{
BluetoothDevice selectedDevice = devices.get(i);
Intent intent=new Intent(getBaseContext(),ConnectedBtActivity.class);
intent.putExtra("MAC",selectedDevice.getAddress());
startActivity(intent);
}
}
});
private void pairDevice(BluetoothDevice device) {
try {
Method m = device.getClass().getMethod("createBond", (Class[]) null);
m.invoke(device, (Object[]) null);
} catch (Exception e) {
Toast.makeText(getBaseContext(),"Exception: "+e.getMessage(),Toast.LENGTH_LONG ).show();
}
}
Here listView contain all the available devices, listAdapter is an ArrayAdapter which contain the available device name and for pair device concate "(Paired)" with device name.
You can clearly see I want to open a new activity if the device already paired and if not paired then initiate the pairing process. Now issue is that pairDevice() is a multi threaded process that means does not wait until the pairing is complete. I want to listen whether the pairing is done or not after that new activity should open.
For better clarification I am posting full code:
public class MyBluetoothScanActivity extends AppCompatActivity{
Button bt,bt_count;
ListView listView;
BluetoothAdapter btAdapter;
Set<BluetoothDevice> devicesArray;
public static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
IntentFilter filter;
BroadcastReceiver receiver;
ArrayAdapter<String> listAdapter;
ArrayList<String> pairedDevices;
ArrayList<BluetoothDevice> devices;
int count=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_bluetooth_scan);
bt=(Button) findViewById(R.id.bT_scan2);
bt.setTransformationMethod(null);
bt_count=(Button) findViewById(R.id.bt_count);
bt_count.setTransformationMethod(null);
bt_count.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getBaseContext(),"Count: "+count,Toast.LENGTH_SHORT ).show();
}
});
listView=(ListView) findViewById(R.id.listViewscan);
btAdapter = BluetoothAdapter.getDefaultAdapter();
filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
if(!btAdapter.isEnabled()){
turnOnBT();
}
init();
bt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
newScan();
}
});
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
if(btAdapter.isDiscovering()){
btAdapter.cancelDiscovery();
}
if(!listAdapter.getItem(i).contains("Paired")){
try {
BluetoothDevice selectedDevice = devices.get(i);
pairDevice(selectedDevice);
Intent intent=new Intent(getBaseContext(),ConnectedBtActivity.class);
intent.putExtra("MAC",selectedDevice.getAddress());
startActivity(intent);
}
catch (Exception e){}
}
else{
BluetoothDevice selectedDevice = devices.get(i);
Intent intent=new Intent(getBaseContext(),ConnectedBtActivity.class);
intent.putExtra("MAC",selectedDevice.getAddress());
startActivity(intent);
}
}
});
}
private void newScan(){
btAdapter.cancelDiscovery();
Toast.makeText(getBaseContext(),"New Scan Start",Toast.LENGTH_SHORT ).show();
listAdapter= new ArrayAdapter<String>(getBaseContext(), android.R.layout.simple_list_item_1,0);
listView.setAdapter(listAdapter);
devices = new ArrayList<BluetoothDevice>();
btAdapter.startDiscovery();
}
private void getPairedDevices() {
devicesArray = btAdapter.getBondedDevices();
if(devicesArray.size()>0){
for(BluetoothDevice device:devicesArray){
pairedDevices.add(device.getName());
}
}
}
void turnOnBT(){
Intent intent =new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivity(intent);
}
void init(){
receiver = new BroadcastReceiver(){
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Toast.makeText(getBaseContext(),"new br: "+action,Toast.LENGTH_LONG ).show();
if(BluetoothDevice.ACTION_FOUND.equals(action)){
pairedDevices=new ArrayList<String>();
getPairedDevices();
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
Toast.makeText(getBaseContext(),"Dev: "+device.getName(),Toast.LENGTH_LONG ).show();
devices.add(device);
String s = "";
for(int a = 0; a < pairedDevices.size(); a++){
if(device.getName().equals(pairedDevices.get(a))){
//append
s = "(Paired)";
break;
}
}
listAdapter.add(device.getName()+" "+s+" "+"\n"+device.getAddress());
}
else if(BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)){
if(btAdapter.getState() == btAdapter.STATE_OFF){
turnOnBT();
}
}
}
};
registerReceiver(receiver, filter);
filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
registerReceiver(receiver, filter);
filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(receiver, filter);
filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
registerReceiver(receiver, filter);
}
private void pairDevice(BluetoothDevice device) {
try {
Method m = device.getClass().getMethod("createBond", (Class[]) null);
m.invoke(device, (Object[]) null);
} catch (Exception e) {
Toast.makeText(getBaseContext(),"Exception: "+e.getMessage(),Toast.LENGTH_LONG ).show();
}
}
#Override
protected void onDestroy() {
super.onDestroy();
try {
Toast.makeText(getBaseContext(),"Un registration",Toast.LENGTH_SHORT ).show();
unregisterReceiver(receiver);
}
catch (Exception e){}
}
}
You can also register for ACTION_BOND_STATE_CHANGED broadcast and check its extra fields to check the result of the bonding process.
Related
I tried and followed some tutorial on web but it didn't work on new Android versions.
I declared all Bluetooth permissions and used Dexter permission library. I followed few answers but it doesn't display available Bluetooth device name also
Below is my code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
scan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
toast("starts scanning...");
mBluetoothAdapter.startDiscovery();
}
});
mAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1);
mListView.setAdapter(mAdapter);
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
String bluetoothDevice = mAdapter.getItem(i);
toast(bluetoothDevice);
}
});
}
public void pairedDevicesListView(View view){
mAdapter.clear();
pairedDevices = mBluetoothAdapter.getBondedDevices();
for (BluetoothDevice device : pairedDevices){
mAdapter.add(device.getName() + "\n" + device.getAddress());
}
}
}
To discover a device, first get the bluetooth adapter by calling BluetoothAdapter.getDefaultAdapter()
BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
To start discover, simply call the startDiscovery() from bluetooth adapter. This process is asynchronous so it will return immediately. To catch the discovery process, we can register a BroadcastReceiver with ACTION_FOUND, ACTION_DISCOVERY_STARTED, ACTION_DISCOVERY_STARTED. For each device found, the intent will carry extra field EXTRA_DEVICE containg the BluetoothDevice object.
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(mReceiver, filter);
adapter.startDiscovery();
The receiver:
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
//discovery starts, we can show progress dialog or perform other tasks
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
//discovery finishes, dismis progress dialog
} else if (BluetoothDevice.ACTION_FOUND.equals(action)) {
//bluetooth device found
BluetoothDevice device = (BluetoothDevice) intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
showToast("Found device " + device.getName());
}
}
};
And, don’t forget to unregister the receiver on Activity’s onDestroy method:
#Override
public void onDestroy() {
unregisterReceiver(mReceiver);
super.onDestroy();
}
Add manifest permissions as follows
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />`
and try following code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnstart=findViewById(R.id.btnstart);
mListView=findViewById(R.id.listofdevices);
final ArrayAdapter mAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1);
mListView.setAdapter(mAdapter);
txt1=findViewById(R.id.txt1);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
setdevicevisible();
boolean hasBluetooth = getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH);
if(!hasBluetooth) {
AlertDialog dialog = new AlertDialog.Builder(MainActivity.this).create();
dialog.setTitle(getString(R.string.bluetooth_not_available_title));
dialog.setMessage(getString(R.string.bluetooth_not_available_message));
dialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Closes the dialog and terminates the activity.
dialog.dismiss();
MainActivity.this.finish();
}
});
dialog.setCancelable(false);
dialog.show();
}
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions((Activity) this,
new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
1);
}
// If another discovery is in progress, cancels it before starting the new one.
if (mBluetoothAdapter.isDiscovering()) {
mBluetoothAdapter.cancelDiscovery();
}
mBluetoothAdapter.startDiscovery();
mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
//Finding devices
if (BluetoothDevice.ACTION_FOUND.equals(action))
{
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// Add the name and address to an array adapter to show in a ListView
mAdapter.add(device.getName() + "\n" + device.getAddress());
}
}
};
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter);
}
I forgot to declare Location permissions in the manifest file. To discover Bluetooth devices programmatically you need to add two permission i.e. ACCESS_FINE_LOCATION and ACCESS_COARSE_LOCATION.
You could use the MAC address as unique ID.
And you can find in the official doc here a complete example of it
https://developer.android.com/guide/topics/connectivity/bluetooth.html#FindingDevices
About signal strength i think you should use RSSI (Received Signal Strength Indicator)
Edit: An easy way to accomplish this will be like this snippet to find bluetooth devices
mBluetoothAdapter.startDiscovery();
mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
//Finding devices
if (BluetoothDevice.ACTION_FOUND.equals(action))
{
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// Add the name and address to an array adapter to show in a ListView
mArrayAdapter.add(device.getName() + "\n" + device.getAddress());
}
}
};
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter);
hope it helps
happy coding
Try using this code, it worked for me.
public class DeviceListActivity extends Activity {
private ListView pairedDevicesListView, newDevicesListView;
private ArrayList<DeviceData> dataList= new ArrayList<DeviceData>();
private ArrayList<BluetoothDevice> pairedDevices=new ArrayList<BluetoothDevice>();
private BluetoothAdapter bluetoothAdapter;
BluetoothDevice device;
private ArrayAdapter newDeviceAdapter;
private DeviceListAdapter pairedDeviceAdapter;
public static String DEVICE_ADDRESS = "device_address";
private IntentFilter filter;
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Log.e("action", action);
// Toast.makeText(DeviceListActivity.this, action, Toast.LENGTH_SHORT).show();
device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (action.equals(BluetoothDevice.ACTION_FOUND)) {
device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
newDeviceAdapter.add(device.getName() + "\n" + device.getAddress());
pairedDevices.add(device);
newDeviceAdapter.notifyDataSetChanged();
}
} else if (action.equals(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)) {
if (newDeviceAdapter.getCount() == 0) {
Toast.makeText(DeviceListActivity.this, "No devices found", Toast.LENGTH_SHORT).show();
newDeviceAdapter.add("No new device found");
newDeviceAdapter.notifyDataSetChanged();
}
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_device_list);
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
pairedDevicesListView = (ListView) findViewById(R.id.avail_devices);
newDevicesListView=(ListView)findViewById(R.id.new_devices);
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
pairedDeviceAdapter = new DeviceListAdapter(this,dataList, pairedDevices);
pairedDevicesListView.setAdapter(pairedDeviceAdapter);
pairedDeviceAdapter.notifyDataSetChanged();
//-----------------------------------------------
newDeviceAdapter=new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
newDevicesListView.setAdapter(newDeviceAdapter);
newDeviceAdapter.notifyDataSetChanged();
if (bluetoothAdapter.isDiscovering()) {
bluetoothAdapter.cancelDiscovery();
}
bluetoothAdapter.startDiscovery();
// get paired devices
Set<BluetoothDevice> pairedDevice = bluetoothAdapter.getBondedDevices();
if(pairedDevice.size()>0)
{
// pairedDeviceAdapter.clear();
for(BluetoothDevice device : pairedDevice)
{
// pairedDeviceAdapter.add(device.getName()+ "\n" +device.getAddress());
dataList.add(new DeviceData(device.getName(),device.getAddress()));
pairedDevices.add(device);
}
pairedDeviceAdapter.notifyDataSetChanged();
}
// register broadcast receiver
filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(broadcastReceiver, filter);
pairedDevicesListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
bluetoothAdapter.cancelDiscovery();
String data = ((TextView) view).getText().toString();
String address = data.substring(data.length() - 17);
Intent intent = new Intent();
intent.putExtra("device_address", address);
intent.putExtra("info", data);
setResult(Activity.RESULT_OK, intent);
finish();
}
});
newDevicesListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
bluetoothAdapter.cancelDiscovery();
Boolean isBonded = false;
try {
isBonded = createBond(device);
if(isBonded)
{
Log.i("Log","Paired");
// pairedDeviceAdapter.add(device.getName() + "\n" + device.getAddress());
dataList.add(new DeviceData(device.getName(),device.getAddress()));
newDeviceAdapter.remove(device.getName() + "\n" + device.getAddress());
pairedDeviceAdapter.notifyDataSetChanged();
newDeviceAdapter.notifyDataSetChanged();
// Toast.makeText(DeviceListActivity.this, "paired to:" +device.getName(), Toast.LENGTH_SHORT).show();
// ------------------------
// Intent intent = new Intent();
// intent.putExtra("device_address", device.getAddress());
// intent.putExtra("info", device.getName());
// setResult(Activity.RESULT_OK, intent);
// finish();
}
} catch (Exception e)
{
e.printStackTrace();
}
}
});
}
#Override
protected void onStart() {
super.onStart();
registerReceiver(broadcastReceiver, filter);
}
#Override
protected void onPostResume() {
super.onPostResume();
registerReceiver(broadcastReceiver, filter);
}
#Override
protected void onDestroy() {
super.onDestroy();
if (bluetoothAdapter != null) {
bluetoothAdapter.cancelDiscovery();
}
this.unregisterReceiver(broadcastReceiver);
}
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();
}
}
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");
Can any one tell me the callback method the bellow code. Is there any other efficient code available for this purpose???
private void pairDevice(BluetoothDevice device) {
try {
Method m = device.getClass().getMethod("createBond", (Class[]) null);
m.invoke(device, (Object[]) null);
} catch (Exception e) {
Toast.makeText(getBaseContext(),"Exception: "+e.getMessage(),Toast.LENGTH_LONG ).show();
}
}
For better clarification I added the full code. I want to do something on the pairing completion
public class BtScan extends AppCompatActivity {
Button bt;
ListView listView;
BluetoothAdapter btAdapter;
Set<BluetoothDevice> devicesArray;
IntentFilter filter;
BroadcastReceiver receiver;
ArrayAdapter<String> listAdapter;
ArrayList<String> pairedDevices;
ArrayList<BluetoothDevice> devices;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_bluetooth_scan);
BluetoothManager bluetoothManager =
(BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
btAdapter = bluetoothManager.getAdapter();
if (!btAdapter.isEnabled()) {
turnOnBT();
}
SharedPreferences prefs = getSharedPreferences("Selected bt", MODE_PRIVATE);
String tmp=prefs.getString("mac","");
if(!tmp.equals("")){
Intent intent=new Intent(getBaseContext(),BtIns.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
intent.putExtra("MAC",tmp);
startActivity(intent);
}
else {
bt = (Button) findViewById(R.id.my_bT_scan);
bt.setTransformationMethod(null);
listView = (ListView) findViewById(R.id.my_listViewscan);
newScan();
bt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
newScan();
}
});
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
if (btAdapter.isDiscovering()) {
btAdapter.cancelDiscovery();
}
SharedPreferences.Editor editor = getSharedPreferences("Selected bt", MODE_PRIVATE).edit();
editor.putString("mac", devices.get(i).getAddress());
editor.commit();
if (!listAdapter.getItem(i).contains("Paired")) {
try {
BluetoothDevice selectedDevice = devices.get(i);
pairDevice(selectedDevice);
Thread.sleep(500);
newScan();
} catch (Exception e) {
}
} else {
BluetoothDevice selectedDevice = devices.get(i);
Intent intent = new Intent(getBaseContext(), BtIns.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
intent.putExtra("MAC", selectedDevice.getAddress());
startActivity(intent);
}
}
});
}
}
private void newScan(){
btAdapter.cancelDiscovery();
Toast.makeText(getBaseContext(),"New Scan Start",Toast.LENGTH_SHORT ).show();
listAdapter= new ArrayAdapter<String>(getBaseContext(), android.R.layout.simple_list_item_1,0);
listView.setAdapter(listAdapter);
devices = new ArrayList<BluetoothDevice>();
btAdapter.startDiscovery();
}
private void getPairedDevices() {
devicesArray = btAdapter.getBondedDevices();
if(devicesArray.size()>0){
for(BluetoothDevice device:devicesArray){
pairedDevices.add(device.getName());
}
}
}
void turnOnBT(){
Intent intent =new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivity(intent);
}
void init(){
receiver = new BroadcastReceiver(){
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
//Toast.makeText(getBaseContext(),"new br: "+action,Toast.LENGTH_LONG ).show();
if(BluetoothDevice.ACTION_FOUND.equals(action)){
pairedDevices=new ArrayList<String>();
getPairedDevices();
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
//Toast.makeText(getBaseContext(),"Dev: "+device.getName(),Toast.LENGTH_LONG ).show();
devices.add(device);
String s = "";
for(int a = 0; a < pairedDevices.size(); a++){
if(device.getName().equals(pairedDevices.get(a))){
//append
s = "(Paired)";
break;
}
}
listAdapter.add(device.getName()+" "+s+" "+"\n"+device.getAddress());
}
else if(BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)){
if(btAdapter.getState() == btAdapter.STATE_OFF){
turnOnBT();
}
}
}
};
}
private void pairDevice(BluetoothDevice device) {
try {
Method m = device.getClass().getMethod("createBond", (Class[]) null);
m.invoke(device, (Object[]) null);
} catch (Exception e) {
Toast.makeText(getBaseContext(),"Exception: "+e.getMessage(),Toast.LENGTH_LONG ).show();
}
}
#Override
protected void onDestroy() {
super.onDestroy();
try {
btAdapter.cancelDiscovery();
unregisterReceiver(receiver);
}
catch (Exception e){}
}
#Override
protected void onPause() {
super.onPause();
try {
btAdapter.cancelDiscovery();
unregisterReceiver(receiver);
}
catch (Exception e){}
}
#Override
public void onResume() {
super.onResume();
try {
init();
registerReceiver(receiver, new IntentFilter(BluetoothDevice.ACTION_FOUND));
registerReceiver(receiver, new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_STARTED));
registerReceiver(receiver, new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED));
registerReceiver(receiver, new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED));
//Toast.makeText(getBaseContext(),"Registration",Toast.LENGTH_SHORT ).show();
}
catch (Exception e){}
}
}
M a Beginner so i dont know how to handle this.
Can someone pls help me out.
This is my error Message. I dont know how to handle this.
Activity application.web.drj.MainActivity has leaked IntentReceiver application.web.drj.MainActivity$1#d33c9c8 that was originally registered here. Are you missing a call to unregisterReceiver()?
public class MainActivity extends ActionBarActivity {
int enablebt = 1;
ListView view1;
BluetoothAdapter adap;
List<BluetoothDevice> connected;
BluetoothSocket mmsocket;
BluetoothDevice mmdevice;
private static final UUID MY_UUID = UUID.fromString("0000110E-0000-1000-8000-00805F9B34FB");
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
adap = BluetoothAdapter.getDefaultAdapter();
connected = new ArrayList<>();
view1 = (ListView) findViewById(R.id.list_item);
if(adap == null)
{
Toast.makeText(this, "This device does not support Bluetooth.", Toast.LENGTH_SHORT).show();
}
if(!adap.isEnabled())
{
Intent enableadap = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableadap,enablebt);
}
final Set<BluetoothDevice> devices = adap.getBondedDevices();
if(devices.size() > 0)
{
for(BluetoothDevice device : devices)
{
connected.add(device);
view1.setAdapter(new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, connected));
}
final BroadcastReceiver 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);
connected.add(device);
}
}
};
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(receiver,filter);
Intent discoverable = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
startActivity(discoverable);
adap.cancelDiscovery();
view1.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, final int position, long id)
{
Thread initialize_connection = new Thread()
{
#Override
public void run()
{
view1.setClickable(false);
BluetoothSocket tmp;
BluetoothDevice initialize_connection = (BluetoothDevice) view1.getItemAtPosition(position);
try
{
tmp = initialize_connection.createRfcommSocketToServiceRecord(MY_UUID);
mmsocket = tmp;
}
catch(Exception e)
{
Toast.makeText(getApplicationContext(),"Runtime Error",Toast.LENGTH_SHORT).show();
}
try
{
mmsocket.connect();
if(mmsocket.isConnected())
{
Toast.makeText(getApplicationContext(),"Connection successfull",Toast.LENGTH_SHORT).show();
}
}
catch(IOException e)
{
Toast.makeText(getApplicationContext(),"Connection Exception",Toast.LENGTH_SHORT).show();
}
super.run();
}
};
initialize_connection.start();
}
});
}
}
You are registering a broadcast receiver in onCreate().
So, its compulsory that you make a call to unregisterReceiver() in onDestroy() at the least.
Since you are registering a broadcast receiver in onCreate() you have to call unregisterReceiver() in onDestroy().
I am using bluetooth in my app, i want my app ti search for new devices and make pair with them and then send a predefined message to them, this is what i did so far :
1- this is the function that initialize my Bluetooth variables
public void BlutoothInit()
{
BlutoothListView=(ListView)findViewById(R.id.minimal_profile);
pairedDevices = new ArrayList<String>();
filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
receiver = new BroadcastReceiver(){
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(BluetoothDevice.ACTION_FOUND.equals(action)){
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
devices.add(device);
String s = "";
for(int a = 0; a < pairedDevices.size(); a++){
if(device.getName().equals(pairedDevices.get(a))){
s = "(Paired)";
break;
}
}
listAdapter.add(device.getName()+" "+s+" "+"\n"+device.getAddress());
}
else if(BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)){
}
else if(BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)){
}
else if(BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)){
if(btAdapter.getState() == btAdapter.STATE_OFF){
//turnOnBT();
}
}
}
};
registerReceiver(receiver, filter);
filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
registerReceiver(receiver, filter);
filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(receiver, filter);
filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
registerReceiver(receiver, filter);
}
2- her i am using Bluetooth
public void via_bluetooth (View v) {
getPairedDevices();
final ListView DevicesListView = (ListView) findViewById(R.id.minimal_profile);
ArrayAdapter<String> adapter;
adapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,DevicesList);
DevicesListView.setAdapter(adapter);
adapter.notifyDataSetChanged();
DevicesListView.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
Toast.makeText(getApplicationContext(), "device is not paired", 0).show();
return true;
}
});
}
the function "getPairedDevices" works fine and i get all the devices that i made pair with from outside my app
but when i call this function to scan new devices
public void ScanNewDevices(View v) {
// TODO Auto-generated method stub
if (btAdapter.isDiscovering()) {
btAdapter.cancelDiscovery();
}
btAdapter.startDiscovery();
try{
final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// When discovery finds a device
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// Add the name and address to an array adapter to show in a ListView
DevicesList.add(device.getName() + "\n" + device.getAddress());
}
}
};
// Register the BroadcastReceiver
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter); // Don't forget to unregister during onDestroy
}
catch (Exception e) {
Toast.makeText(getApplicationContext(), e.toString(), 0).show();
}
}
an error says "Source not found." appears and do nothing !!!
whats iam doing wrong and what is missing to search for devices and send them a message ?
private void pairDevice(BluetoothDevice device) {
try {
Method m = device.getClass().getMethod("createBond", (Class[]) null);
m.invoke(device, (Object[]) null);
Toast.makeText(context,"paired finished",3000).show();
} catch (Exception e)
{
Toast.makeText(context,"error"+e.getMessage(),3000).show();
}
}
//try this for paring...