Manifest file -:
<uses-permission android:name="[Link]" />
<uses-permission android:name="[Link].BLUETOOTH_ADMIN" />
<uses-permission android:name="[Link].ACCESS_FINE_LOCATION" />
XML File -:
<RelativeLayout xmlns:android="[Link]
xmlns:tools="[Link]
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="@+id/btnScan"
android:text="Scan for Devices"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_alignParentTop="true" />
<ListView
android:id="@+id/lvDevices"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@id/btnScan" />
</RelativeLayout>
[Link]
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class MainActivity extends AppCompatActivity {
private static final int REQUEST_BLUETOOTH = 1;
private BluetoothAdapter bluetoothAdapter;
private ArrayAdapter<String> adapter;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
[Link](savedInstanceState);
setContentView([Link].activity_main);
bluetoothAdapter = [Link]();
Button btnScan = findViewById([Link]);
ListView lvDevices = findViewById([Link]);
adapter = new ArrayAdapter<>(this, [Link].simple_list_item_1);
[Link](adapter);
[Link](new [Link]() {
@Override
public void onClick(View v) {
startBluetooth();
}
});
}
private void startBluetooth() {
if (bluetoothAdapter == null) {
[Link](this, "Bluetooth not supported", Toast.LENGTH_SHORT).show();
return;
}
if (![Link]()) {
Intent enableBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBluetooth, REQUEST_BLUETOOTH);
} else {
scanForDevices();
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
[Link](requestCode, resultCode, data);
if (requestCode == REQUEST_BLUETOOTH && resultCode == RESULT_OK) {
scanForDevices();
}
}
private void scanForDevices() {
[Link]();
Set<BluetoothDevice> pairedDevices = [Link]();
if ([Link]() > 0) {
for (BluetoothDevice device : pairedDevices) {
[Link]([Link]() + " - " + [Link]());
}
}
}
}