Here's an example of a simple Bluetooth Android application in Java. This example demonstrates how to discover nearby Bluetooth devices and establish a connection with one of them.
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Set;
import java.util.UUID;
public class BluetoothActivity extends Activity {
private BluetoothAdapter bluetoothAdapter;
private ArrayAdapter<String> discoveredDevicesArrayAdapter;
private ArrayList<BluetoothDevice> discoveredDevices;
private BluetoothSocket bluetoothSocket = null;
private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); // UUID for SPP (Serial Port Profile)
private static final int REQUEST_ENABLE_BT = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bluetooth);
// Initialize Bluetooth adapter
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter == null) {
Toast.makeText(this, "Bluetooth is not supported on this device", Toast.LENGTH_SHORT).show();
finish();
return;
}
// Check if Bluetooth is enabled, and request to enable it if not
if (!bluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
// Initialize UI components
Button discoverButton = findViewById(R.id.discoverButton);
ListView discoveredDevicesListView = findViewById(R.id.discoveredDevicesListView);
discoveredDevicesArrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1);
discoveredDevices = new ArrayList<>();
discoveredDevicesListView.setAdapter(discoveredDevicesArrayAdapter);
// Register for broadcasts when a device is discovered
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(discoveryReceiver, filter);
// Set up item click listener for discovered devices list
discoveredDevicesListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
// Connect to the selected device
BluetoothDevice selectedDevice = discoveredDevices.get(position);
connectToDevice(selectedDevice);
}
});
// Set up discover button click listener
discoverButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
discoverDevices();
}
});
}
@Override
protected void onDestroy() {
super.onDestroy();
// Unregister the broadcast receiver
unregisterReceiver(discoveryReceiver);
}
// Discover nearby Bluetooth devices
private void discoverDevices() {
if (bluetoothAdapter.isDiscovering()) {
bluetoothAdapter.cancelDiscovery();
}
bluetoothAdapter.startDiscovery();
}
// Connect to a Bluetooth device
private void connectToDevice(BluetoothDevice device) {
try {
bluetoothSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
bluetoothSocket.connect();
// You can now send/receive data through the BluetoothSocket
// For example, use InputStream and OutputStream to communicate with the device
Toast.makeText(this, "Connected to " + device.getName(), Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(this, "Failed to connect to " + device.getName(), Toast.LENGTH_SHORT).show();
}
}
// Broadcast receiver for handling device discovery
private final BroadcastReceiver discoveryReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// A Bluetooth device has been discovered
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (device != null) {
discoveredDevices.add(device);
discoveredDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
}
}
}
};
}
In this example, we create an Android application that can discover nearby Bluetooth devices, display them in a list, and establish a connection with the selected device when an item in the list is clicked.
Make sure to add the necessary Bluetooth permissions to your AndroidManifest.xml file:
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT"/>
Additionally, you should have appropriate layout XML files (e.g., activity_bluetooth.xml
) and add Bluetooth-related UI elements to them.
Remember that Bluetooth programming can be complex, and this is just a basic example to get you started. You will need to handle error cases, manage Bluetooth state changes, and implement data communication as per your specific requirements.