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();
Related
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.");
}
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){}
}
}
I wanted to start with the basics of bluetooth connection and make a simple app capable of scanning, pairing and connecting.
I'm struggling with the last concept, i followed a lot of tutorials but I couldn't make it. I don't know if you can help me but here is my code.
ublic class MainActivity extends Activity {
private final String TAG = "Debugging";
private final static int REQUEST_CODE_ENABLE_BLUETOOTH = 0;
protected static final int SUCCESS_CONNECT = 0;
protected static final int MESSAGE_READ = 1;
public static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
BluetoothAdapter btAdapter;
ArrayList<String> arrayListpaired;
ArrayAdapter<String> listAdapter,adapter;
ListView listView,listViewPaired;
Set<BluetoothDevice> deviceArray;
ArrayList<String> pairedDevices;
IntentFilter filter;
BroadcastReceiver receiver;
BluetoothDevice bdDevice;
ArrayList<BluetoothDevice> arrayListBluetoothDevices = null;
ArrayList<BluetoothDevice> arrayListPairedBluetoothDevices;
ListItemClicked listItemClicked;
ListItemClickedonPaired listItemClickedonPaired;
String tag = "debugging";
Handler mHandler= new Handler() {
public void handleMessage(Message msg){
super.handleMessage(msg);
switch(msg.what){
case SUCCESS_CONNECT:
ConnectedThread connectedThread = new ConnectedThread((BluetoothSocket)msg.obj);
Toast.makeText(getApplicationContext(),"Connect",Toast.LENGTH_LONG).show();
String s= "Succesfully connected";
connectedThread.write(s.getBytes());
Log.i(tag, "connected");
break;
case MESSAGE_READ:
byte[] readbuff=(byte[])msg.obj;
String string= readbuff.toString();
Toast.makeText(getApplicationContext(), string,Toast.LENGTH_SHORT).show();
break;
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btAdapter = BluetoothAdapter.getDefaultAdapter();
arrayListBluetoothDevices = new ArrayList<BluetoothDevice>();
arrayListpaired = new ArrayList<String>();
arrayListPairedBluetoothDevices = new ArrayList<BluetoothDevice>();
adapter= new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, arrayListpaired);
listItemClickedonPaired = new ListItemClickedonPaired();
listViewPaired = (ListView) findViewById(R.id.listView3);
listItemClicked = new ListItemClicked();
listView = (ListView) findViewById(R.id.listView2);
listAdapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_activated_1);
listView.setAdapter(listAdapter);
listAdapter.notifyDataSetChanged();
listViewPaired.setAdapter(adapter);
setupMessageButton1();
setupMessageButton2();
setupMessageButton3();
setupMessageButton4();
setupMessageButton5();
init();
getPairedDevices();
}
private void init() {
listView.setOnItemClickListener(listItemClicked);
listViewPaired.setOnItemClickListener(listItemClickedonPaired);
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)) {
Toast.makeText(getApplicationContext(), "One Device Found", Toast.LENGTH_SHORT).show();
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (arrayListBluetoothDevices.size() < 1) // this checks if the size of bluetooth device is 0,then add the
{ // device to the arraylist.
listAdapter.add(device.getName() + "\n" + device.getAddress());
arrayListBluetoothDevices.add(device);
listAdapter.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) {
listAdapter.add(device.getName() + "\n" + device.getAddress());
arrayListBluetoothDevices.add(device);
listAdapter.notifyDataSetChanged();
}
}
}
}
};
registerReceiver(receiver, filter);
}
private void createBond(BluetoothDevice btDevice){
try
{
Method method = btDevice.getClass().getMethod("createBond", (Class[]) null);
method.invoke(btDevice, (Object[]) null);
}
catch (Exception e)
{
e.printStackTrace();
}
}
private void unpairDevice(BluetoothDevice device) {
try {
Method method = device.getClass().getMethod("removeBond", (Class[]) null);
method.invoke(device, (Object[]) null);
} catch (Exception e) {
e.printStackTrace();
}
}
private void getPairedDevices() {
Set<BluetoothDevice> pairedDevice = btAdapter.getBondedDevices();
if(pairedDevice.size()>0)
{
for(BluetoothDevice device : pairedDevice)
{
arrayListpaired.add(device.getName()+"\n"+device.getAddress());
arrayListPairedBluetoothDevices.add(device);
}
}
adapter.notifyDataSetChanged();
}
public 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);
Log.i("Log", "The device : " + bdDevice.toString());
getPairedDevices();
createBond(bdDevice);
adapter.notifyDataSetChanged();
Log.i("Log", "The bond is created: with" + bdDevice.toString());
}
}
private class ConnectThread extends Thread {
private final BluetoothSocket mmSocket;
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() {
btAdapter.cancelDiscovery();
try {
mmSocket.connect();
} catch (IOException connectException) {
try {
mmSocket.close();
} catch (IOException closeException) { }
return;
}
mHandler.obtainMessage(SUCCESS_CONNECT, mmSocket).sendToTarget();
}
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) { }
}
}
#Override
protected void onDestroy() {
super.onDestroy();
btAdapter.cancelDiscovery();
unregisterReceiver(receiver);
}
class ListItemClickedonPaired implements OnItemClickListener
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
bdDevice = arrayListPairedBluetoothDevices.get(position);
unpairDevice(bdDevice);
//arrayListPairedBluetoothDevices.clear();
}
}
private void makeDiscoverable() {
Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 150);
startActivity(discoverableIntent);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_CANCELED) {
Toast.makeText(MainActivity.this, "Bluetooth must be enabled to start scanning", Toast.LENGTH_SHORT).show();
} else
{
Toast.makeText(MainActivity.this, "Click on TURN_OFF to disable bluetooth", Toast.LENGTH_LONG).show();
}
}
private void setupMessageButton1() {
//1.get a reference for my button
Button messageButton = (Button) findViewById(R.id.button1);
//2. Set the click to run my code
messageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
listAdapter.clear();
arrayListBluetoothDevices.clear();
btAdapter.startDiscovery();
}
});
}
private void setupMessageButton2() {
//1.get a reference to the button.
Button messageButton = (Button) findViewById(R.id.button2);
//2. set the click listener to run my code.
messageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (btAdapter.isEnabled()) {
listAdapter.clear();
btAdapter.disable();
} else
{
Toast.makeText(MainActivity.this, "Dont worry it's already off", Toast.LENGTH_SHORT).show();
}
}
});
}
private void setupMessageButton3() {
//1.get a reference for my button
Button messageButton = (Button) findViewById(R.id.button3);
//2. Set the click to run my code
messageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
private void setupMessageButton4() {
//1.get a reference for my button
Button messageButton = (Button) findViewById(R.id.button4);
//2. Set the click to run my code
messageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
btAdapter.enable();
}
});
}
private void setupMessageButton5() {
//1.get a reference for my button
Button messageButton = (Button) findViewById(R.id.button5);
//2. Set the click to run my code
messageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
makeDiscoverable();
}
});
}
}
Concerning the log i have that message :
"D/BluetoothUtils﹕ isSocketAllowedBySecurityPolicy start : device null"
"W/BluetoothAdapter﹕ getBluetoothService() called with no BluetoothManagerCallback"
"D/BluetoothSocket﹕ connect(), SocketState: INIT, mPfd: {ParcelFileDescriptor: FileDescriptor[75]} "
public 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);
Log.i("Log", "The device : " + bdDevice.toString());
createBond(bdDevice);
adapter.notifyDataSetChanged();
ConnectThread connect = new ConnectThread(bdDevice);
connect.start();
}
}
For the connection, i use the ConnectThread found in Bluetooth APi developer Website:
private class ConnectThread extends Thread {
private final BluetoothSocket mmSocket;
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() {
btAdapter.cancelDiscovery();
try {
mmSocket.connect();
} catch (IOException connectException) {
try {
mmSocket.close();
} catch (IOException closeException) { }
return;
}
mHandler.obtainMessage(SUCCESS_CONNECT, mmSocket).sendToTarget();
}
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}
}
it's ok i found the solution, i had the problem with the phone i'm using, he is not supporting SPP.
Thank you anyway
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
}