0% found this document useful (0 votes)
6 views4 pages

22

The document is a Java class for an Android application that scans for Bluetooth devices. It includes functionality to request permissions, display found devices in a list, and connect to a selected device with confirmation. The app utilizes a BroadcastReceiver to handle Bluetooth device discovery and maintains a list of connected devices using a HashMap.

Uploaded by

dprocraft
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views4 pages

22

The document is a Java class for an Android application that scans for Bluetooth devices. It includes functionality to request permissions, display found devices in a list, and connect to a selected device with confirmation. The app utilizes a BroadcastReceiver to handle Bluetooth device discovery and maintains a list of connected devices using a HashMap.

Uploaded by

dprocraft
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 4

package com.example.

abcc;

import android.Manifest;
import android.app.AlertDialog;
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.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.UUID;

public class BluetoothScanDevices extends AppCompatActivity {


Button btn_cancel;
ImageButton imb_reload;
ListView listView;
BluetoothAdapter bluetoothAdapter;
ArrayList<String> deviceList = new ArrayList<>();
ArrayAdapter<String> adapter ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bluetooth_scan_devices);
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1,
deviceList);
btn_cancel = findViewById(R.id.btn_cancel);
listView = findViewById(R.id.list_view_bluetooth);
imb_reload = findViewById(R.id.imb_reload);
listView.setAdapter(adapter);

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {


ActivityCompat.requestPermissions(this, new String[]{
android.Manifest.permission.BLUETOOTH_SCAN,
Manifest.permission.BLUETOOTH_CONNECT
}, 1);
}
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(bluetoothReceiver, filter);

startBluetoothScan();
//
imb_reload.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startBluetoothScan();
}
});
btn_cancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
String selectedDevice = deviceList.get(position);
String[] deviceInfo = selectedDevice.split("\n");
String deviceName = deviceInfo[0];
String deviceMacAddress = deviceInfo[1];
// Hiển thị hộp thoại xác nhận
new AlertDialog.Builder(BluetoothScanDevices.this)
.setTitle("Connect Confirm")
.setMessage("Are you sure you want to connect to " +
deviceName + "?")
.setPositiveButton("Yes", (dialog, which) -> {
connectToDevice(deviceMacAddress);
})
.setNegativeButton("Cancel", (dialog, which) ->
dialog.dismiss())
.show();
}
});
}

private void connectToDevice(String deviceMacAddress) {


if (ActivityCompat.checkSelfPermission(this,
Manifest.permission.BLUETOOTH_SCAN) != PackageManager.PERMISSION_GRANTED) {
return;
}
if (bluetoothAdapter.isDiscovering()) {
bluetoothAdapter.cancelDiscovery();
}
if (MainActivity.listMacConnected.contains(deviceMacAddress)){
Toast.makeText(this, "This device is already connect",
Toast.LENGTH_SHORT).show();
return;
}
MainActivity.listMacConnected.add(deviceMacAddress);
BluetoothDevice device =
bluetoothAdapter.getRemoteDevice(deviceMacAddress);
try {
// Tạo BluetoothSocket để kết nối tới thiết bị
BluetoothSocket socket =
device.createRfcommSocketToServiceRecord(UUID.fromString("00001101-0000-1000-8000-
00805F9B34FB"));
// Kết nối đến thiết bị
socket.connect();
// Lưu socket vào HashMap với key là device MAC Address
MainActivity.socketMap.put(deviceMacAddress, socket);
//BluetoothSocket socket = socketMap.get(deviceMacAddress);
Toast.makeText(this, "Connect Successful" + device.getName(),
Toast.LENGTH_SHORT).show();

// Khi kết nối thành công, bạn có thể gửi kết quả về Activity chính
if (socket.isConnected()) {
String deviceName = device.getName(); // Lấy tên thiết bị

// Gửi tên thiết bị và MAC về MainActivity


Intent resultIntent = new Intent();
resultIntent.putExtra("connection_success", true);
resultIntent.putExtra("device_name", deviceName); // Gửi tên thiết
bị
resultIntent.putExtra("deviceMacAddress", deviceMacAddress);
setResult(RESULT_OK, resultIntent);
finish();
}

} catch (IOException e) {
Toast.makeText(this, "Fail to connect!", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}

private void startBluetoothScan() {


deviceList.clear();
adapter.notifyDataSetChanged();
if (ActivityCompat.checkSelfPermission(this,
Manifest.permission.BLUETOOTH_SCAN) != PackageManager.PERMISSION_GRANTED) {
return;
}
bluetoothAdapter.startDiscovery();
Toast.makeText(this, "Scanning Devices...", Toast.LENGTH_SHORT).show();
}
private final BroadcastReceiver bluetoothReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device =
intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (ActivityCompat.checkSelfPermission(context,
Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
return;
}
String deviceInfo = (device.getName() != null ? device.getName() :
"No name Device") +
"\n" + device.getAddress();
if (!deviceList.contains(deviceInfo)) {
deviceList.add(deviceInfo);
adapter.notifyDataSetChanged();
}
}
}
};

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy