Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to make Bluetooth Connection in Android?

    • 0
    • 0
    • 0
    • 0
    • 1
    • 0
    • 0
    • 0
    • 1.87k
    Comment on it

    Bluetooth connectivity in Android is achieved through the APIs provided by Android itself. You need a broadcast receiver to keep checking for the Bluetooth devices.
    With the help of broadcast you will get to know whether your device get connected, disconnected or has finished the discovery.
    Next, you need to have a Asynctask to make a Bluetooth connection.

    Steps to Establish Bluetooth Connection in Android

    Below are the three steps through which you can establish a Bluetooth connection:

    1) First you need to create Broadcast Receiver for keep scanning the devices you want to detect. This you can declare in your onCreate method.

    mReceiver = new BroadcastReceiver() 
            { 
                public void onReceive(Context context, Intent intent) 
                { 
                    String action = intent.getAction(); 
                    // When discovery finds a device 
                    if (BluetoothDevice.ACTION_FOUND.equals(action)) 
                    { 
                        // Get the BluetoothDevice object from the Intent 
                        BluetoothDevice device = intent.getParcelableExtra( 
                                BluetoothDevice.EXTRA_DEVICE); 
                       Log.i("DEVICE NAME:"+ device.getName()); 
                        boolean checkfordevice =false; 
                        if(device.getName()!= null){ 
                            for (int i = 0; i < deviceList.size(); i++) { 
                                if(deviceList.get(i).getAddress().equalsIgnoreCase(device.getAddress())){ 
                                    checkfordevice = true; 
                                    break; 
                                } 
                            } 
                            if(!checkfordevice){ 
                                deviceList.add(device); 
                            } 
                            ((BaseAdapter)deviceListView.getAdapter()).notifyDataSetChanged(); 
                        } 
                    } 
                    else if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)){ 
                        Toast.makeText(getApplicationContext(), "Device Connected", Toast.LENGTH_SHORT).show();
                    } 
                    else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) { 
                        Toast.makeText(getApplicationContext(), "FINISHED", Toast.LENGTH_SHORT).show();   
                    } 
                    else if (BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED.equals(action)) { 
                        Toast.makeText(getApplicationContext(), "REQUEST DISCONNECTED", Toast.LENGTH_SHORT).show();   
    
                    } 
                    else if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) { 
                         Toast.makeText(getApplicationContext(), "DISCONNECTED", Toast.LENGTH_SHORT).show(); 
                    }        
                }    
            }; 
    

    2) On a button click, you can call this below method to scan the Bluetooth devices.

    private void scanBluetoothDevices() { 
            // TODO Auto-generated method stub 
            mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); 
            String aDiscoverable = BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE; 
            startActivityForResult(new Intent(aDiscoverable),DISCOVERY_REQUEST); 
            IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND); 
            getActivity().registerReceiver(mReceiver, filter); 
            mBluetoothAdapter.startDiscovery(); 
        } 
    

    3) Below is the Asynctask for Bluetooth Connection. The connection of Bluetooth should always be done in AsyncTask class because it will create its own thread for Bluetooth connection and will not impact the main thread. Hence making it a better performing application.

    private class BluetoothAsyncTask extends AsyncTask<String, Void, String>{
            private int position;
            private ProgressDialog dialog;
            BluetoothAsyncTask(int mPosition){
                this.position = mPosition;
                dialog = new ProgressDialog(getActivity());
            }
    
            @Override
            protected void onPreExecute(){
                this.dialog.setMessage("Connecting");
                this.dialog.show();
            }
    
            @Override
            protected String doInBackground(String... params) {
                // TODO Auto-generated method stub
                mBluetoothAdapter.cancelDiscovery();
                Method m;
                try {
                    m = deviceList.get(position).getClass().getMethod("createRfcommSocket", new Class[] { int.class });
                    socket = (BluetoothSocket) m.invoke(deviceList.get(position), 1);
                    socket.connect();
                    inputData = socket.getInputStream(); 
                    outputData = socket.getOutputStream();
                    return "Success";
                } catch (NoSuchMethodException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    return "Failed";
                }
            }
    
            @Override 
            protected void onPostExecute(String result){ 
                if(this.dialog.isShowing()){ 
                    this.dialog.dismiss(); 
                } 
                if(result =="Success"){ 
                      Toast.makeText(getApplicationContext(), "Connection successful", Toast.LENGTH_SHORT).show(); 
                 // You will get a toast message on successful bluetooth connection
                } 
            }        
        }
    

 1 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: