android bluetooth pairing callback method - android

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

Related

Android Studio Bluetooth ListView

I wanted to make bluetooth applications for arduino so that I could connect to the HC-05 module. And I found a tutorial on how to make a bluetooth connection (http://mcuhq.com/27/simple-android-bluetooth-application-with-arduino-example) When I downloaded the code from github, the application starts and everything works and connects. But the problem is that I can't open a new activity because the project is probably for 15 API and the new activity needs at least 16 so I decided to make such an application on my own based on the code from this website. And here I have a problem because when I make my phone search for bluetooth devices, nothing is displayed on my ListView.
This is my code `
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
offon = findViewById(R.id.BtBtn);
TV = findViewById(R.id.BtTv);
TV2 = findViewById(R.id.textView2);
TV3 = findViewById(R.id.bluetooth_status);
Next = findViewById(R.id.button2);
LV = findViewById(R.id.ListView);
disc = findViewById(R.id.button3);
ArrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1);
adapter = BluetoothAdapter.getDefaultAdapter();
LV.setAdapter(ArrayAdapter);
LV.setOnItemClickListener(DeviceList);
handler = new Handler(Looper.getMainLooper()){
#Override
public void handleMessage(Message msg){
if(msg.what == MESSAGE_READ){
String readMessage = null;
readMessage = new String((byte[]) msg.obj, StandardCharsets.UTF_8);
TV2.setText(readMessage);
}
if(msg.what == CONNECTING_STATUS){
char[] sConnected;
if(msg.arg1 == 1)
TV3.setText(getString(R.string.BTConnected) + msg.obj);
else
TV3.setText(getString(R.string.BTconnFail));
}
}
};
if (adapter.isEnabled()){
TV.setText("Bluetooth ON");
}else TV.setText("Bluetooth OFF");
disc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
discovery();
if (!adapter.isEnabled()){
Toast.makeText(getBaseContext(), getString(R.string.BTnotOn), Toast.LENGTH_SHORT).show();
}
}
});
offon.setOnClickListener(new View.OnClickListener() {
#SuppressLint("MissingPermission")
#Override
public void onClick(View view) {
if (adapter.isEnabled()) {
adapter.disable();
TV.setText("Bluetooth OFF");
}else {
adapter.enable();
TV.setText("Bluetooth ON");
}
}
});
Next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
open2activity();
}
});
}
public void open2activity(){
Intent intent = new Intent(this, MainActivity2.class);
startActivity(intent);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent Data) {
super.onActivityResult(requestCode, resultCode, Data);
}
#SuppressLint("MissingPermission")
private void discovery(){
if (adapter.isDiscovering()){
adapter.cancelDiscovery();
Toast.makeText(getApplicationContext(), getString(R.string.DisStop), Toast.LENGTH_SHORT).show();
}
else{
if (adapter.isEnabled()){
ArrayAdapter.clear();
adapter.startDiscovery();
Toast.makeText(getApplicationContext(), getString(R.string.DisStart), Toast.LENGTH_SHORT).show();
registerReceiver(blReceiver, new IntentFilter(BluetoothDevice.ACTION_FOUND));
}
}
}
final BroadcastReceiver blReceiver = new BroadcastReceiver() {
#SuppressLint("MissingPermission")
#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);
ArrayAdapter.add(device.getName() + "\n" + device.getAddress());
ArrayAdapter.notifyDataSetChanged();
}
}
};
private AdapterView.OnItemClickListener DeviceList = new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TV3.setText(getString(R.string.cConnet));
String info = ((TextView)view).getText().toString();
final String address = info.substring(info.length() - 17);
final String name = info.substring(0,info.length() - 17);
new Thread()
{
#SuppressLint("MissingPermission")
#Override
public void run() {
boolean fail = false;
BluetoothDevice device = adapter.getRemoteDevice(address);
try {
BTSocket = createBluetoothSocket(device);
} catch (IOException e) {
fail = true;
Toast.makeText(getBaseContext(), getString(R.string.ErrSockCrea), Toast.LENGTH_SHORT).show();
}
try {
BTSocket.connect();
} catch (IOException e) {
try {
fail = true;
BTSocket.close();
handler.obtainMessage(CONNECTING_STATUS, -1, -1)
.sendToTarget();
} catch (IOException e2) {
Toast.makeText(getBaseContext(), getString(ErrSockCrea), Toast.LENGTH_SHORT).show();
}
}
if(!fail) {
ConnectedThread = new ConnectedThread(BTSocket, handler);
ConnectedThread.start();
handler.obtainMessage(CONNECTING_STATUS, 1, -1, name)
.sendToTarget();
}
}
}.start();
}
};
#SuppressLint("MissingPermission")
private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException {
try {
final Method m = device.getClass().getMethod("createInsecureRfcommSocketToServiceRecord", UUID.class);
return (BluetoothSocket) m.invoke(device, BT_MODULE_UUID);
} catch (Exception e) {
Log.e(TAG, "Could not create Insecure RFComm Connection",e);
}
return device.createRfcommSocketToServiceRecord(BT_MODULE_UUID);
}
}
`
I tried to do as above but nothing is displayed

Bluetooth scanning working but available Bluetooth devices are not found

I am using an Android 9 Pie API level. I am sending an available device using intent to another activity from below code using Broadcast in multiple ways.
Paired device list show perfectly but available nearby device not found when the search finishes. But don't know why it is not working.
private ActivityMainBinding binding;
private ArrayList<BluetoothDevice> mDeviceList = new ArrayList<>();
private BluetoothAdapter mBluetoothAdapter;
private ProgressDialog mProgressDlg;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
mProgressDlg = new ProgressDialog(this);
mProgressDlg.setMessage("Scanning Device");
mProgressDlg.setCancelable(false);
mProgressDlg.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
mBluetoothAdapter.cancelDiscovery();
}
});
if (mBluetoothAdapter == null) {
showUnsupported();
} else {
binding.btnViewPaired.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
if (pairedDevices == null || pairedDevices.size() == 0) {
showToast("No Paired Devices Found");
} else {
ArrayList<BluetoothDevice> list = new ArrayList<>();
list.addAll(pairedDevices);
Intent intent = new Intent(MainActivity.this, DeviceListActivity.class);
intent.putParcelableArrayListExtra("device.list", list);
startActivity(intent);
}
}
});
binding.btnScan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
mBluetoothAdapter.startDiscovery();
}
});
binding.btnEnable.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mBluetoothAdapter.isEnabled()) {
mBluetoothAdapter.disable();
showDisabled();
} else {
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(intent, 1000);
}
}
});
if (mBluetoothAdapter.isEnabled()) {
showEnabled();
} else {
showDisabled();
}
}
///////////////////////////////////////////////////////////////////////////////////////////
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
filter.addAction(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(mReceiver, filter);
}
#Override
public void onPause() {
if (mBluetoothAdapter != null) {
if (mBluetoothAdapter.isDiscovering()) {
mBluetoothAdapter.cancelDiscovery();
}
}
super.onPause();
}
#Override
public void onDestroy() {
unregisterReceiver(mReceiver);
super.onDestroy();
}
private void showEnabled() {
binding.tvStatus.setText("Bluetooth is On");
binding.tvStatus.setTextColor(Color.GREEN);
binding.btnEnable.setText("Disable");
binding.btnEnable.setEnabled(true);
binding.btnViewPaired.setEnabled(true);
binding.btnScan.setEnabled(true);
}
private void showDisabled() {
binding.tvStatus.setText("Bluetooth is Off");
binding.tvStatus.setTextColor(Color.RED);
binding.btnEnable.setText("Enable");
binding.btnEnable.setEnabled(true);
binding.btnViewPaired.setEnabled(false);
binding.btnScan.setEnabled(false);
}
private void showUnsupported() {
binding.tvStatus.setText("Bluetooth is unsupported by this device");
binding.btnEnable.setText("Enable");
binding.btnEnable.setEnabled(false);
binding.btnViewPaired.setEnabled(false);
binding.btnScan.setEnabled(false);
}
private void showToast(String message) {
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
}
///// Boradcast recever to handle
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {
final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR);
if (state == BluetoothAdapter.STATE_ON) {
showToast("Bluetooth Enabled");
showEnabled();
}
} else if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
mDeviceList = new ArrayList<>();
mProgressDlg.show();
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
mProgressDlg.dismiss();
Intent newIntent = new Intent(MainActivity.this, DeviceListActivity.class);
newIntent.putParcelableArrayListExtra("device.list", mDeviceList);
startActivity(newIntent);
} else if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
mDeviceList.add(device);
showToast("Found device " + device.getName());
}
}
};

Unable to connect to the Bluetooth?

I am trying to connect to another Bluetooth through programmatically in android but continuously I am getting this error. anyone, please help me to connect Bluetooth. is there anything wrong with my code. i am working with bluetooth from last 2 weeks but unable to connect to the bluetooth.
is there working source code availble in github it may be helpful for me
Error-> BluetoothAdapter: getBluetoothService() called withBluetoothManagerCallback
BluetoothAdapter mBluetoothAdapter;
BluetoothDevice mBluetoothDevice;
ListView paired_lv;
Button paired_btn, listen, sendData;
TextView deviceTxt;
ClientSocket socket;
ConnectedThread connectedThread;
private static final UUID MY_UUID_SECURE =
UUID.fromString("fa87c0d0-afac-11de-8a39-0800200c9a66");
private static final UUID MY_UUID_INSECURE =
UUID.fromString("8ce255c0-200a-11e0-ac64-0800200c9a66");
private static final UUID BTMODULEUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
paired_btn = findViewById(R.id.paired_devices);
paired_lv = findViewById(R.id.paired_lv);
deviceTxt = findViewById(R.id.device_name);
listen = findViewById(R.id.listen);
sendData = findViewById(R.id.send_data);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null){
toast("Your device doesn't support bluetooth adapter");
}else if (!mBluetoothAdapter.isEnabled()){
mBluetoothAdapter.enable();
}
paired_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
pairedDevices();
}
});
paired_lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
BluetoothDevice device = (BluetoothDevice) adapterView.getItemAtPosition(i);
toast("clicket"+device.getName() );
socket = new ClientSocket(device);
socket.start();
}
});
listen.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// AcceptThread acceptThread = new AcceptThread();
//acceptThread.start();
if (socket != null){
socket.cancel();
}
}
});
sendData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String mes = "bhanu";
Log.d("BT","Send button clicked");
connectedThread.write("bhanu");
}
});
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);
filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
registerReceiver(mReceiver,filter);
}
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)){
Log.d("BT","device connected");
toast("device connected");
}else if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)){
toast("device disconnected");
}
}
};
public void toast(String message){
Toast.makeText(getApplicationContext(),message,Toast.LENGTH_SHORT).show();
}
public void pairedDevices(){
Set<BluetoothDevice> devices = mBluetoothAdapter.getBondedDevices();
ArrayList<BluetoothDevice> arrayList = new ArrayList<>();
if (devices.size()<0){
toast("no paired devices found");
}else {
for (BluetoothDevice device:devices){
toast(device.getName());
arrayList.add(device);
ArrayAdapter<BluetoothDevice> adapter = new ArrayAdapter<>(getApplicationContext(),android.R.layout.simple_list_item_1,arrayList);
paired_lv.setAdapter(adapter);
}
}
}
private class ClientSocket extends Thread{
private final BluetoothDevice mDevice;
private final BluetoothSocket mSocket;
public ClientSocket(BluetoothDevice device,Boolean isSecure) {
mDevice = device;
BluetoothSocket tmp = null;
boolean secure = isSecure;
try {
tmp = device.createInsecureRfcommSocketToServiceRecord(MY_UUID_INSECURE);
} catch (IOException e) {
e.printStackTrace();
}
mSocket = tmp;
}
#Override
public void run() {
mBluetoothAdapter.cancelDiscovery();
if (mDevice.getBondState() == BluetoothDevice.BOND_BONDED){
Log.d("BT","bonded");
}
if (BluetoothDevice.DEVICE_TYPE_LE == mDevice.getType()){
try {
Log.d("BT","Connecting BT");
Log.d("BT","socket info"+ mSocket);
mSocket.connect();
Log.d("BT","Connected BT");
} catch (IOException e) {
cancel();
e.printStackTrace();
}
}
if (mSocket != null){
connectedThread = new ConnectedThread(mSocket);
}
}
public void cancel(){
if (mSocket.isConnected()){
try {
mSocket.close();
Log.d("BT","socket was closed");
} catch (IOException e) {
e.printStackTrace();
}
}else {
Log.d("BT","device not connected to the any other device");
}
}
}
private class AcceptThread extends Thread{
private final BluetoothServerSocket mServerSocket;
public AcceptThread() {
BluetoothServerSocket tmp = null;
try {
tmp = mBluetoothAdapter.listenUsingInsecureRfcommWithServiceRecord("Bhanu",MY_UUID_INSECURE);
} catch (IOException e) {
e.printStackTrace();
}
mServerSocket = tmp;
}
#Override
public void run() {
BluetoothSocket socket = null;
while (true){
try {
//Toast.makeText(getApplicationContext(),"ready to accept",Toast.LENGTH_SHORT).show();
Log.d("BT","ready to accept socket");
socket = mServerSocket.accept();
Log.d("BT","socket accepted");
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
#Override
protected void onDestroy() {
unregisterReceiver(mReceiver);
super.onDestroy();
}
}
You need a BluetoothManager
BluetoothManager mBluetoothManager;
if (mBluetoothManager == null) {
mBluetoothManager = (BluetoothManager) getSystemService(this);
if (mBluetoothManager == null) {
Log.e(TAG, "Unable to initialize BluetoothManager.");
}
}
mBluetoothAdapter = mBluetoothManager.getAdapter();
if (mBluetoothAdapter == null) {
Log.e(TAG, "Unable to obtain a BluetoothAdapter.");
}

how to establish a Bluetooth connection in a listView android

While I am trying to connect to the Bluetooth device in a listview, I am getting error
in listview I am passing Bluetooth device to the second class it extends thread. Error:
getBluetoothService() called with no BluetoothManagerCallback,
ListViewCompat.lookForSelectablePosition(int, boolean) would have incorrectly overridden the package-private method in android.widget
Button PairedBT, ScanBt;
ListView pairedListView;
public BluetoothAdapter mBluetoothAdapter;
ArrayAdapter<String> mAdapter;
ArrayList<String> mArrayList = new ArrayList<String>();
BluetoothDevice[] btArray = new BluetoothDevice[30];
//ArrayList<BluetoothDevice> connectDevice = new ArrayList<BluetoothDevice>();
UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
PairedBT = findViewById(R.id.pairedBt);
pairedListView = findViewById(R.id.list_view_paired);
ScanBt = findViewById(R.id.scanBt);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
PairedBT.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Set<BluetoothDevice> devices = mBluetoothAdapter.getBondedDevices();
String[] names = new String[devices.size()];
int index = 0;
if (devices.size() > 0) {
for (BluetoothDevice device : devices) {
names[index] = device.getName();
index++;
}
//mAdapter = new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_list_item_1,names);
// pairedListView.setAdapter(mAdapter);
}
}
});
ScanBt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mBluetoothAdapter.startDiscovery();
}
});
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
filter.addAction(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter);
mAdapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, mArrayList);
pairedListView.setAdapter(mAdapter);
pairedListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//pairDevice(btArray[i]);
BluetoothDevice device = btArray[i];
// BluetoothDevice device = (BluetoothDevice) pairedListView.getAdapter().getItem(i);
ClientSocket clientSocket = new ClientSocket(device);
Toast.makeText(getApplicationContext(), "at" + btArray[i], Toast.LENGTH_SHORT).show();
//mBluetoothAdapter.cancelDiscovery();
clientSocket.start();
//sendBT();
}
});
}
BroadcastReceiver mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String acton = intent.getAction();
toast("onReceive method");
int i = 0;
if (BluetoothDevice.ACTION_FOUND.equals(acton)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
btArray[i] = device;
i++;
//connectDevice.add(device);
mArrayList.add(device.getName());
toast("found");
mAdapter.notifyDataSetChanged();
}
}
};
#Override
protected void onDestroy() {
unregisterReceiver(mReceiver);
super.onDestroy();
}
#Override
protected void onPause() {
if (mBluetoothAdapter.isDiscovering()) {
mBluetoothAdapter.cancelDiscovery();
}
super.onPause();
}
public void toast(String message) {
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
}
public void sendBT() {
OutputStream out = null;
String sample = "Welcome to qualtech";
// out.write(sample.getBytes());
}
private void pairDevice(BluetoothDevice device) {
try {
Method method = device.getClass().getMethod("createBond", (Class[]) null);
method.invoke(device, (Object[]) null);
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
private void unPairDevice(BluetoothDevice device) {
Method method = null;
try {
method = device.getClass().getMethod("removeBond", (Class[]) null);
method.invoke(device, (Object) null);
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
private class ClientSocket extends Thread {
private BluetoothDevice mDevice;
private BluetoothSocket mSocket;
private boolean mSecure;
// private BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
public ClientSocket(BluetoothDevice device) {
mDevice = device;
BluetoothSocket tmp = null;
mBluetoothAdapter.cancelDiscovery();
try {
Log.d("BT", "BT creating RfcommSocketService");
tmp = mDevice.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e) {
e.printStackTrace();
}
mSocket = tmp;
}
public void run() {
mBluetoothAdapter.cancelDiscovery();
try {
Log.d("BT", "BT Connecting");
mSocket.connect();
Log.d("BT", "Connected succesufully");
} catch (IOException e) {
e.printStackTrace();
}
}
public void cancel() {
try {
mSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Try moving your intent filter code (6 lines of code) above mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

android bluetooth pairing request and wait for success

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.

Categories

Resources