3

I am new to Android and I am trying to understand the working of Bluetooth connection. For that I have used used the wiced sense app to understand the working.

Here I want to connect to a particular device with respect to their MAC address. I have managed to store and retrieve the MAC address through Shared preferences. And now I want to connect to device which matches the MAC address without user interaction.

To store the MAC address I do the following:

 public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;

        if (convertView == null || convertView.findViewById(R.id.device_name) == null) {
            convertView = mInflater.inflate(R.layout.devicepicker_listitem, null);
            holder = new ViewHolder();
            String DeviceName;

            holder.device_name = (TextView) convertView.findViewById(R.id.device_name);
          //  DeviceName= String.valueOf((TextView) convertView.findViewById(R.id.device_name));
            holder.device_addr = (TextView) convertView.findViewById(R.id.device_addr);
            holder.device_rssi = (ProgressBar) convertView.findViewById(R.id.device_rssi);

            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        DeviceRecord rec = mDevices.get(position);
        holder.device_rssi.setProgress(normaliseRssi(rec.rssi));
        editor = PreferenceManager.getDefaultSharedPreferences(mContext);
        String deviceName = rec.device.getName();
        if (deviceName != null && deviceName.length() > 0) {
            holder.device_name.setText(rec.device.getName());
            holder.device_addr.setText(rec.device.getAddress());
            //Log.i(TAG, "Service onStartCommand");
            if(deviceName.equals("eVulate")&& !editor.contains("MAC_ID")) {
                storeMacAddr(String.valueOf(rec.device.getAddress()));
               }
        } else {
            holder.device_name.setText(rec.device.getAddress());
            holder.device_addr.setText(mContext.getResources().getString(R.string.unknown_device));
        }

        return convertView;

 public void storeMacAddr(String MacAddr) {

        editor.edit().putString("MAC_ID", MacAddr).commit();
    }
        }

I retrive the same through the following code :

private void initDevicePicker() {           
        final SharedPreferences mSharedPreference= PreferenceManager.getDefaultSharedPreferences(getBaseContext());
       if(mSharedPreference.contains("MAC_ID")){
        String value=(mSharedPreference.getString("MAC_ID", ""));
        }
        else
          // search for devices
}

I want to start a service after retrieving the MAC address and I don't know where exactly to do that. Any kind of help is appreciated.

ADI
  • 91
  • 1
  • 4
  • 13
  • I saw one of the answer which suits to my situation [here](http://stackoverflow.com/questions/15025852/how-to-move-bluetooth-activity-into-a-service) . If anyone can provide me some more details especially with MyApplication and Abstract class it would be really helpful. – ADI Apr 29 '16 at 14:30

2 Answers2

1

All you have the MAC addresses of some bluetooth devices and you want to connect to them using their MAC addresses. I think you need to read more about bluetooth discovery and connection but anyway, I'm putting some code which might help you later after reading about Android bluetooth.

From your Activity you need to register a BroadcastReceiver so identify the bluetooth connection changes and to start discovering nearby bluetooth devices. The BroadcastReceiver will look like this

private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {

        } else if (BluetoothDevice.ACTION_FOUND.equals(action)) {
            BluetoothDevice device = (BluetoothDevice) intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

            if (device.getAddress().equals(Constants.DEVICE_MAC_ADDRESS)) {
                startCommunication(device);
            }

        } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {


        } else if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
            // Your bluetooth device is connected to the Android bluetooth

        } else if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) {
            // Your device is disconnected. Try connecting again via startDiscovery
            mBluetoothAdapter.startDiscovery();
        }
    }
};

There's a startCommunication function inside I'll post it later in this answer. Now you need to register this BroadcastReceiver in your activity.

Inside your onCreate register the receiver like this

// Register bluetooth receiver
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);
filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
filter.addAction(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(mReceiver, filter);

Don't forget to unregister the receiver inside onDestroy function of your Activity

unregisterReceiver(mReceiver);

Now in your Activity you need to declare a BluetoothAdapter to start bluetooth discovery and a BluetoothSocket to make connection with the bluetooth. So you need to add these two variables in your Activity and initialize them accordingly.

// Declaration
public static BluetoothSocket mmSocket;
public static BluetoothAdapter mBluetoothAdapter;

...

// Inside `onCreate` initialize the bluetooth adapter and start discovering nearby BT devices
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
mBluetoothAdapter.enable();
mBluetoothAdapter.startDiscovery();

Now here you go for the startCommunication function

void startCommunication(BluetoothDevice device) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        ConnectThread mConnectThread = new ConnectThread(device);
        mConnectThread.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
    } else {
        ConnectThread mConnectThread = new ConnectThread(device);
        mConnectThread.execute((Void) null);
    }
}

The ConnectThread is an AsyncTask which connects to a desired device in a different thread and opens a BluetoothSocket for communication.

public class ConnectThread extends AsyncTask<Void, Void, String> {

    private BluetoothDevice btDevice;

    public ConnectThread(BluetoothDevice device) {
        this.btDevice = device;
    }

    @Override
    protected String doInBackground(Void... params) {

        try {
            YourActivity.mmSocket = btDevice.createRfcommSocketToServiceRecord(Constants.MY_UUID);
            YourActivity.mBluetoothAdapter.cancelDiscovery();
            YourActivity.mmSocket.connect();

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

        return "";
    }

    @Override
    protected void onPostExecute(final String result) {

        if (result != null){/* Success */}
        else {/* Connection Failed */}

    }

    @Override
    protected void onCancelled() {}

}

This is how you can find the nearby bluetooth device and connect to them by using the MAC addresses stored previously.

Reaz Murshed
  • 23,691
  • 13
  • 78
  • 98
  • Thank you fro the information. But, I want to include the bluetooth connectivity in a service. I do this because once the app gets disconnected the service should start running and search for the device with MAC address and then connect to it(If available). How do I implement the above code in a service.? – ADI Apr 29 '16 at 11:45
-1

After String value=(mSharedPreference.getString("MAC_ID", "")); you can start service. Here all thing that you required for Getting data and send data to Bluetooth device.

Sanjay Kakadiya
  • 1,596
  • 1
  • 15
  • 32
  • This question is not subjected to BLE. So please update your answer or remove it – Reaz Murshed Apr 29 '16 at 10:24
  • @ReazMurshed Read question it is subjected to Bluetooth connection. – Sanjay Kakadiya Apr 29 '16 at 10:28
  • I didn't downvote your answer. Anyway, the question is about bluetooth connection - YES! There's a basic difference between bluetooth and BLE. And please, mention some working codes whenever you answer a question in SO. – Reaz Murshed Apr 29 '16 at 10:48