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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With