I am working on a Bluetooth control App using Android , when the user click the Pair button to start the connection with another Bluetooth device , i want to open another activity after amount of time ( when the pairing between the two devices is finished) .
The problem is that the App is stopped after pairing between devices . what is the problem in my code ? i have searched a lot but i havent found any solution .Please any help would be appreciated .
thanks in advance
this is my code
public class DevicesListActivity extends Activity
{
private ListView mListView;
private DeviceListAdapter mAdapter;
//the List that we will receive from the Main Activity
private ArrayList<BluetoothDevice> PassedDeviceList;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_devices_list);
PassedDeviceList = getIntent().getExtras().getParcelableArrayList("device.list");
mListView = (ListView) findViewById(R.id.DevicesList_lv);
mAdapter = new DeviceListAdapter(this);
mAdapter.setData(PassedDeviceList);
mAdapter.setListener(new DeviceListAdapter.OnPairButtonClickListener() {
#Override
public void onPairButtonClick(int position)
{
showToast("PairedBTN Clicked");
BluetoothDevice device = PassedDeviceList.get(position);
if (device.getBondState() == BluetoothDevice.BOND_BONDED)
{
unpairDevice(device);
}
else
{
showToast("Pairing...");
pairDevice(device);
}
}
});
mListView.setAdapter(mAdapter);
registerReceiver(mPairReceiver, new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED));
}
//***** We will Pair with the Selected Device then Go to the Control Screen
private void pairDevice(final BluetoothDevice device)
{
try
{
Method method = device.getClass().getMethod("createBond", (Class[]) null);
method.invoke(device, (Object[]) null);
showToast("YOu have Paired with Device Name:" + device.getName()+" And Address: " + device.getAddress() );
//***** Make an intent to start next activity.*****
new Handler().postDelayed(new Runnable() {
public void run() {
Intent i = new Intent(DevicesListActivity.this, MobileControl.class);
//Change the activity.
String address = device.getAddress();
i.putExtra("ADDRESS", address); //this will be received at Control Activity
startActivity(i);
//finish();
}
}, 10000);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
Related
I create app which work with bluetooth and almost everything is ok but one this is not cool. So after I connect device do some staff save everything them disconnect it, my app stops seeing this device is no more on my list, but after 5-10 minutes device back on the list. What can be the issue?
public class MainActivity extends AppCompatActivity {
static final int SEND_TIMES = 1;
static final int SEND_DATE = 2;
List<BluetoothDevice> devices;
Spinner devicesSpinner = null;
BluetoothAdapter bluetoothAdapter = null;
BluetoothSocket clientSocket = null;
OutputStream outputData = null;
InputStream inputData = null;
List<String> devicesNames = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (!bluetoothAdapter.isEnabled()) {
Intent enableRequest = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivity(enableRequest);
}
findDevices();
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(deviceFoundReceiver, filter);
registerReceiver(bondStateChangeReceiver, filter);
devices = new ArrayList();
devicesSpinner = findViewById(R.id.devices_list);
devicesSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
try {
if(devices.get(i) == null)
return;
BluetoothDevice remoteDevice = bluetoothAdapter.getRemoteDevice(devices.get(i).getAddress());
Method m = remoteDevice.getClass().getMethod("createRfcommSocket", new Class[]{int.class});
clientSocket = (BluetoothSocket) m.invoke(remoteDevice, 1);
outputData = clientSocket.getOutputStream();
inputData = clientSocket.getInputStream();
} catch (Exception e){
Log.i("REMOTE_DEVICE", "No such a method", e);
}
}
#Override
public void onNothingSelected (AdapterView<?> adapterView){
}
});
if(clientSocket != null)
Toast.makeText(this, "" + clientSocket.isConnected(), Toast.LENGTH_LONG);
}
public void connectDevice(View view) throws IOException {
if (isSocketConnected()) return;
bluetoothAdapter.cancelDiscovery();
if(!clientSocket.isConnected()){
try {
clientSocket.connect();
} catch (Exception e){
Toast.makeText(this, "Can not connect to this device try later!", Toast.LENGTH_LONG).show();
return;
}
TextView textView = (TextView) findViewById(R.id.boundedDevice);
textView.setText(clientSocket.getRemoteDevice().getName());
}
}
public void disconnectDevice(View view) throws IOException {
if(clientSocket.isConnected()){
clientSocket.close();
TextView textView = (TextView) findViewById(R.id.boundedDevice);
textView.setText("Device not connected");
}
}
}
That is my code which I am using for connection, what is wrong?
What I want to have is I would like to have my device straight away on my list after disconnection, to not waiting those 5-10 mins to let my app find it again.
This is client-side code and you need server-side code.So you need two device and one device must be a server another device must be a client.If you want to search available device you work in server side.First of all you must look at android developer bluetooth chat project in the official site.Then find out server-side code.
https://developer.android.com/samples/BluetoothChat/project.html
The discovery and pairing process described in the Android Bluetooth Documentation is quite complex. Even a separate permission is needed for that: BLUETOOTH_ADMIN.
I wonder if there is a system action, that I just would call, that will handle the UI, return, and the I will just choose an already paired device. Or do I have to implement all that UI myself?
if you want to get the list of paired bluetooth devices you can use this code
public class DeviceList extends ActionBarActivity
{
//widgets
Button btnPaired;
ListView devicelist;
//Bluetooth
private BluetoothAdapter myBluetooth = null;
private Set<BluetoothDevice> pairedDevices;
public static String EXTRA_ADDRESS = "device_address";
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_device_list);
//Calling widgets
btnPaired = (Button)findViewById(R.id.button);
devicelist = (ListView)findViewById(R.id.listView);
//if the device has bluetooth
myBluetooth = BluetoothAdapter.getDefaultAdapter();
if(myBluetooth == null)
{
//Show a mensag. that the device has no bluetooth adapter
Toast.makeText(getApplicationContext(), "Bluetooth Device Not Available", Toast.LENGTH_LONG).show();
//finish apk
finish();
}
else if(!myBluetooth.isEnabled())
{
//Ask to the user turn the bluetooth on
Intent turnBTon = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(turnBTon,1);
}
btnPaired.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
pairedDevicesList();
}
});
}
private void pairedDevicesList()
{
pairedDevices = myBluetooth.getBondedDevices();
ArrayList list = new ArrayList();
if (pairedDevices.size()>0)
{
for(BluetoothDevice bt : pairedDevices)
{
list.add(bt.getName() + "\n" + bt.getAddress()); //Get the device's name and the address
}
}
else
{
Toast.makeText(getApplicationContext(), "No Paired Bluetooth Devices Found.", Toast.LENGTH_LONG).show();
}
final ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1, list);
devicelist.setAdapter(adapter);
devicelist.setOnItemClickListener(myListClickListener); //Method called when the device from the list is clicked
}
private AdapterView.OnItemClickListener myListClickListener = new AdapterView.OnItemClickListener()
{
public void onItemClick (AdapterView<?> av, View v, int arg2, long arg3)
{
// Get the device MAC address, the last 17 chars in the View
String info = ((TextView) v).getText().toString();
String address = info.substring(info.length() - 17);
// Make an intent to start next activity.
Intent i = new Intent(DeviceList.this, NextActivity.class);
//Change the activity.
i.putExtra(EXTRA_ADDRESS, address); //this will be received at NextActivity
startActivity(i);
}
};
}
I have made an application that allows many-to-one communication using Bluetooth and it is working perfectly fine. Now, i wanted to use the service of the application in another application (e.g. Discovering Devices, Connecting to Device). So, I marked my project as library and added it as library in my new project. However, when i call the Discovering Device Activity (Available in library) from the application, the activity starts, but it doesn't discovers the devices ? Can someone help on this ?
I have included all the library project activity and permissions in my app's manifest.
Here is the sample code for the same -
In Library -
This is how the DeviceListActivity Looks like -
`
public class DeviceListActivity extends Activity{
String insecure="8ce255c0-200a-11e0-ac64-0800200c9a66";
private int flag=0;
int flag_toast=0;
ArrayList<Pair<String,String>> x=new ArrayList<Pair<String,String>>();
private static final String TAG = "DeviceListActivity";
ArrayList<String> temp=new ArrayList<String>();
Map<String, String> services = new HashMap<String, String>();
/**
* Return Intent extra
*/
public static String EXTRA_DEVICE_ADDRESS = "device_address";
/**
* Member fields
*/
private BluetoothAdapter mBtAdapter;
/**
* Newly discovered devices
*/
ImageView animation;
private ArrayList<BluetoothDevice> btDeviceList = new ArrayList<BluetoothDevice>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Setup the window
// requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.activity_device_list);
// Set result CANCELED in case the user backs out
setResult(Activity.RESULT_CANCELED);
// Initialize the button to perform device discovery
animation=(ImageView)findViewById(R.id.imageAnimation);
/*scanButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
doDiscovery();
v.setVisibility(View.GONE);
}
});*/
// Initialize array adapters. One for already paired devices and
// one for newly discovered devices
//ArrayAdapter<String> pairedDevicesArrayAdapter =new ArrayAdapter<String>(this, R.layout.device_name);
//mNewDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.device_name);
//Register for broadcasts when a device is discovered
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothDevice.ACTION_UUID);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(mReceiver, filter);
/* this.registerReceiver(mReceiver, filter);
// Register for broadcasts when discovery has finished
filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
this.registerReceiver(mReceiver, filter);
*/
// Get the local Bluetooth adapter
mBtAdapter = BluetoothAdapter.getDefaultAdapter();
animation.setBackgroundResource(R.drawable.animation);
doDiscovery();
}
#Override
protected void onDestroy() {
super.onDestroy();
// Make sure we're not doing discovery anymore
if (mBtAdapter != null) {
mBtAdapter.cancelDiscovery();
}
// Unregister broadcast listeners
this.unregisterReceiver(mReceiver);
}
/**
* Start device discover with the BluetoothAdapter
*/
public void doDiscovery() {
Log.d(TAG, "doDiscovery()");
// If we're already discovering, stop it
if (mBtAdapter.isDiscovering()) {
mBtAdapter.cancelDiscovery();
}
// Request discover from BluetoothAdapter
mBtAdapter.startDiscovery();
}
private void connect_automatic(String name){
flag++;
Log.d(name,"Called " + Integer.toString(flag)+" times");
Log.d("Flag is = ",Integer.toString(flag));
int i,j;
for(i=0;i<x.size();i++){
for (j=i+1;j<x.size();j++)
if (x.get(i).getFirst().equals(x.get(j).getFirst())==true && x.get(i).getSecond().equals(x.get(j).getSecond())==true)
x.remove(j);
}
for(i=0;i<x.size();i++){
Log.d("Found "+x.get(i).getFirst(),x.get(i).getSecond());
}
Log.d("Size =",Integer.toString(x.size()));
if (x.size()>=1){
Log.d("Size is =",Integer.toString(x.size()));
String address = x.get(0).getFirst();
if (flag_toast==0)
Toast.makeText(DeviceListActivity.this, "Merchant Found", Toast.LENGTH_SHORT).show();
flag_toast++;
Log.d("Connecting to ",x.get(0).getFirst());
// Create the result Intent and include the MAC address
Intent intent = new Intent();
intent.putExtra(EXTRA_DEVICE_ADDRESS, address);
// Set result and finish this Activity
setResult(Activity.RESULT_OK, intent);
finish();
}
}
/**
* The BroadcastReceiver that listens for discovered devices and changes the title when
* discovery is finished
*/
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// When discovery finds a device
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
flag++;
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// If it's already paired, skip it, because it's been listed already
//mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
btDeviceList.add(device);
// When discovery is finished, change the Activity title
}
else
{
Log.d("Action=",action.toString());
if(BluetoothDevice.ACTION_UUID.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
Parcelable[] uuidExtra = intent.getParcelableArrayExtra(BluetoothDevice.EXTRA_UUID);
if(uuidExtra!=null)
for (int i=0; i<uuidExtra.length; i++) {
if(uuidExtra[i].toString().length()>0){
Log.d("\n Device: " + device.getName() + ", " + device, ", Service: " + uuidExtra[i].toString());
// services.put(device.getName(), uuidExtra[i].toString());
//flag=btDeviceList.size();
if (/*uuidExtra[i].toString().equals(secure)==true ||*/ uuidExtra[i].toString().equals(insecure)==true){
Pair<String,String> t=new Pair<String, String>(device.getAddress(), uuidExtra[i].toString());
x.add(t);
}
//connect_automatic();
}
}
Log.d("Device List =",Integer.toString(flag));
connect_automatic(device.getName());
//Log.d("Boolean",Boolean.toString(services.isEmpty()))
}
else
{
if(BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
Log.d("Discovery","Started...");
}
else
{
if(BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
Log.d("Discover","Finished");
//setProgressBarIndeterminateVisibility(false);
Iterator<BluetoothDevice> itr = btDeviceList.iterator();
while (itr.hasNext()) {
// Get Services for paired devices
BluetoothDevice device = itr.next();
temp.add(device.getName());
Log.d("ok","Getting Services for " + device.getName() + ", " + device);
if(!device.fetchUuidsWithSdp()) {
Log.d("!ok","SDP Failed for " + device.getName());
}
else{
Log.d("SDP Passed for ",device.getName());
}
}
//connect_automatic();
}
}
}
}
}
};}`
And here is how i call it in my new application -
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter != null)
{
ensureDiscoverable();
Intent intent = new Intent(this, DeviceListActivity.class);
startActivityForResult(intent, REQUEST_CONNECT_DEVICE_INSECURE);
}
}
I have also posted in android Enthusiasts, not sure if its the correct place..
We have created an app to scan for wifi hotspots / AP so we can read the SSID and RSSI. We have some test phones with hotspot turned on and hard coded the SSID into the app. When the APP launches for the first time all works OK, we click the AP (checkbox) and hit start (button).When we close the app and launch it again, as soon as we click the AP (checkbox) it start scanning even though we haven't click the start button. we need to reinstall the app on the phone every time. Can anyone help us with this BUG/ unwanted feature as its slowing us up.
here is the code for the main Activity.
your help is greatly appreciated.
public class RssiMyActivity extends Activity{
// Declare global variables
private WifiManager mainWifiObj;
private WifiScanReceiver wifiReciever;
private ListView list;
private ArrayAdapter<String> adapter;
private List<String> ap_details = new ArrayList<String>();
private static String ssid;
private int testCount;
private CheckBox a1, a2, a3, a4, a5, a6;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rssi_my);
list = (ListView) findViewById(R.id.listView1);
mainWifiObj = (WifiManager) getSystemService(Context.WIFI_SERVICE);
wifiReciever = new WifiScanReceiver();
// Get make a connection to database to get test count
ReceiveFromDB receiver = new ReceiveFromDB();
receiver.execute();
// Update the test count
testCount = ReceiveFromDB.getCount();
testCount += 1;
// Check to see what value testCount is
Log.e("Values for testCount", String.valueOf(testCount));
Button start;
start = (Button) findViewById(R.id.start);
start.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
// Timer added to get new scan result once every 2 seconds
Timer myTimer = new Timer();
myTimer.schedule(new TimerTask()
{
#Override
public void run()
{
TimerMethod();
}
}, 0, 4000);
}
});
Button pause;
pause = (Button) findViewById(R.id.pause);
pause.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
onPause();
}
});
Button resume;
resume = (Button) findViewById(R.id.resume);
resume.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
onResume();
}
});
a1 = (CheckBox) findViewById(R.id.AP1);
a2 = (CheckBox) findViewById(R.id.AP2);
a3 = (CheckBox) findViewById(R.id.AP3);
a4 = (CheckBox) findViewById(R.id.AP4);
a5 = (CheckBox) findViewById(R.id.AP5);
a6 = (CheckBox) findViewById(R.id.AP6);
}
protected void onPause()
{
unregisterReceiver(wifiReciever);
super.onPause();
}
protected void onResume()
{
registerReceiver(wifiReciever, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
super.onResume();
}
// Timer method to run at the same time as the main activity
private void TimerMethod()
{
this.runOnUiThread(Timer_Tick);
}
/*
* Runnable method add code to here to refresh at specified time
*/
private Runnable Timer_Tick = new Runnable()
{
#Override
public void run()
{
try
{
// start a scan of ap's
mainWifiObj.startScan();
}
catch (Exception e)
{
e.getStackTrace();
}
}
};
class WifiScanReceiver extends BroadcastReceiver
{
#SuppressLint("UseValueOf")
public void onReceive(Context c, Intent intent)
{
// Clear details to refresh the screen for each new scan
if (ap_details.size() > 0)
{
try
{
ap_details.clear();
adapter.clear();
adapter.notifyDataSetChanged();
}
catch (Exception e)
{
e.printStackTrace();
}
}
try
{
// Get all Objects from the scan
List<ScanResult> wifiScanList = mainWifiObj.getScanResults();
List<ScanResult> temp = new ArrayList<ScanResult>();
// Run through each signal and retrieve the mac ssid rssi
for (ScanResult aWifiScanList : wifiScanList)
{
StringBuilder sb = new StringBuilder();
// Pull out the info we need
ssid = aWifiScanList.SSID;
// Check which ap's are selected
if (checkDisplay())
{
// Add info to StringBuilder
sb.append(aWifiScanList.SSID).append("\n");
sb.append(String.valueOf(aWifiScanList.level)).append("\n");
sb.append("Test: ").append(String.valueOf(testCount)).append("\n");
// Add to List that will be displayed to user
ap_details.add(sb.toString());
// Also add to a temporary ScanResult List to use later
temp.add(aWifiScanList);
}
}
// Create an String Array twice the size of the temporary
// ScanResult
// this will be the Array to use as the parameters for sending
// to the database
String[] items = new String[temp.size() + temp.size() + 1];
int num1 = 0;
int num2 = 1;
// Add the ssid and rssi of each object to the Array
for (ScanResult aTemp : temp)
{
items[num1] = aTemp.SSID;
items[num2] = String.valueOf(aTemp.level);
num1 += 2;
num2 += 2;
}
// Add the test value
items[num1] = String.valueOf(testCount);
// Pass Array to the Async method use executeOnExecutor this
// allows for the use
// of the Looper.prepare() method to stop app from crashing
new ConnectToDB().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, items);
// Display the list of all the signals on the device
adapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, ap_details);
list.setAdapter(adapter);
}
catch (Exception e)
{
e.getStackTrace();
}
}
}
/*
* Method to check which AP's are been used
*/
public boolean checkDisplay()
{
if (a1.isChecked())
{
if (ssid.equalsIgnoreCase("TestPhone1"))
{
return true;
}
}
if (a2.isChecked())
{
if (ssid.equalsIgnoreCase("TestPhone2"))
{
return true;
}
}
if (a3.isChecked())
{
if (ssid.equalsIgnoreCase("TestPhone3"))
{
return true;
}
}
if (a4.isChecked())
{
if (ssid.equalsIgnoreCase("TestPhone4"))
{
return true;
}
}
if (a5.isChecked())
{
if (ssid.equalsIgnoreCase("TestPhone5"))
{
return true;
}
}
if (a6.isChecked())
{
if (ssid.equalsIgnoreCase("TestPhone6"))
{
return true;
}
}
return false;
}
You never call cancel() on your timer task to remove it from the Timer scheduler. Try inserting that in a button you use to stop it from scanning.
If that doesn't work, try calling cancel() on the timer itself.
ok got it working, not sure if its the right way but its working ok. I just unregister the reciecer and register it again by calling the two methods "onPause() and onResume()" one after the other and just before the startScan() method. see code:
private Runnable Timer_Tick = new Runnable()
{
#Override
public void run()
{
try
{
// unRegister Receiver wifiReciever
onPause();
// register Receiver wifiReciever
onResume();
// start a scan of ap's
mainWifiObj.startScan();
}
catch (Exception e)
{
e.getStackTrace();
}
}
};
would love to know if this is correct way to do it.
i want to search and listing bluetooth devices in android, my program now able to list all the active devices but not able to send pairing request to the other devices .I want to implement this onItemClick of list element.And also if bluetooth is not enabled of my device then show a permission to active device,if i go for yes then ok,but if i go for no then permission show again until i press yes..how can i do this?plz help with code..here is my code..
public class Main extends Activity {
TextView out;
private static final int REQUEST_ENABLE_BT = 1;
private BluetoothAdapter btAdapter;
private ArrayList<BluetoothDevice> btDeviceList = new ArrayList<BluetoothDevice>();
private ArrayList<String> mylist= new ArrayList<String>();
private ListView lv;
private Button btn;
public Parcelable[] uuidExtra;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void search(View view)
{
//Register the BroadcastReceiver
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothDevice.ACTION_UUID);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(ActionFoundReceiver, filter); // Don't forget to unregister during onDestroy
// Getting the Bluetooth adapter
btAdapter = BluetoothAdapter.getDefaultAdapter();
Toast.makeText(getApplicationContext(),"\nAdapter: " + btAdapter,5000).show();
CheckBTState();
}
private void setDeviceList(ArrayList<String> list) {
lv = (ListView) findViewById(R.id.listView);
ArrayAdapter<String> adapter= new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,list);
lv.setAdapter(adapter);
}
/* This routine is called when an activity completes.*/
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_ENABLE_BT) {
CheckBTState();
}
}
#Override
protected void onDestroy() {
super.onDestroy();
if (btAdapter != null) {
btAdapter.cancelDiscovery();
}
unregisterReceiver(ActionFoundReceiver);
}
private void CheckBTState() {
// Check for Bluetooth support and then check to make sure it is turned on
// If it isn't request to turn it on
// List paired devices
// Emulator doesn't support Bluetooth and will return null
if(btAdapter==null) {
Toast.makeText(getApplicationContext(),"\nBluetooth NOT supported. Aborting.",5000).show();
return;
} else {
if (btAdapter.isEnabled()) {
Toast.makeText(getApplicationContext(),"\nBluetooth is enabled...",5000).show();
// Starting the device discovery
btAdapter.startDiscovery();
} else if (!btAdapter.isEnabled()){
Intent enableBtIntent = new Intent(btAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
/* else{
Intent intent = new Intent(btAdapter.ACTION_STATE_CHANGED);
startActivityForResult(intent, RESULT_CANCELED);
}*/
}
}
private final BroadcastReceiver ActionFoundReceiver = 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);
Toast.makeText(getApplicationContext(),"\n Device: " + device.getName() + ", " + device,5000).show();
mylist.add(device.getName());
setDeviceList(mylist);
} else {
if(BluetoothDevice.ACTION_UUID.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
Parcelable[] uuidExtra = intent.getParcelableArrayExtra(BluetoothDevice.EXTRA_UUID);
for (int i=0; i<uuidExtra.length; i++) {
Toast.makeText(getApplicationContext(),"\n Device: " + device.getName() + ", " + device + ", Service: " + uuidExtra[i].toString(),5000).show();
}
} else {
if(BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
Toast.makeText(getApplicationContext(),"\nDiscovery Started...",5000).show();
} else {
if(BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
Toast.makeText(getApplicationContext(),"\nDiscovery Finished",5000).show();
Iterator<BluetoothDevice> itr = btDeviceList.iterator();
while (itr.hasNext()) {
// Get Services for paired devices
BluetoothDevice device = itr.next();
Toast.makeText(getApplicationContext(),"\nGetting Services for " + device.getName() + ", " + device,5000).show();
if(!device.fetchUuidsWithSdp()) {
Toast.makeText(getApplicationContext(),"\nSDP Failed for " + device.getName(),5000).show();
}
}
}
}
}
}
}
};
}
It's too late but here is code -> You need to use background thread to connect with bluetooth device as a client. and UUID is Universal Uniquely identification you can use online UUID generator. for secure connections and then get socket with device and connect with it;
ConnectWithDevice(context : ConnectWithBluetooth, device : BluetoothDevice) : Thread(){
private val mContext : ConnectWithBluetooth = context
private val mmSocket : BluetoothSocket
private val mmDevice : BluetoothDevice
// Default UUID
private val mmDefaultUUID = UUID.fromString("78c374fd-f84d-4a9e-aa5b-9b0b6292952e")
init {
var temp : BluetoothSocket? = null
mmDevice = device
try {
// Try here device.createInsecureConnect if it's work then start with this;
temp = device.createRfcommSocketToServiceRecord(mmDevice.uuids[0].uuid)
}catch (en : NullPointerException){
en.printStackTrace()
// Try here device.createInsecureConnect if it's work then start with this;
temp = device.createRfcommSocketToServiceRecord(mmDefaultUUID)
}catch (e : IOException){
e.printStackTrace()
Log.e("TAG","Socket's create() method failed",e)
}
mmSocket = temp!!
Log.i("TAG","Got the Socket")
}
override fun run() {
// Cancel discovery because it otherwise slows down the connection.
if(mContext.bluetoothAdapter != null){
mContext.bluetoothAdapter!!.cancelDiscovery()
}
try{
// Connect to the remote device through the socket. This call blocks
// until it succeeds or throws an exception.
Log.i("TAG","Connecting...")
mmSocket.connect()
Log.i("TAG","Bluetooth Successfully Connected")
}catch (connectException : IOException){
// Unable to connect; close the socket and return.
try{
mmSocket.close()
}catch (closeException : IOException){
Log.e("TAG","Could not close the client socket",closeException)
}
return
}
// The connection attempt succeeded. Perform work associated with
// the connection in a separate thread.
Log.i("TAG","Device is Connected")
//manageMyConnectedSocket(mmSocket)
}
// Closes the client socket and causes the thread to finish.
// Call this method from the main activity to shut down the connection.
fun cancel(){
try {
mmSocket.close()
} catch (e: IOException) {
Log.e(ContentValues.TAG, "Could not close the client socket", e)
}
}
}