라 쓰고 나의 삽질 여정기라 읽는다

 

1. 블루투스 퍼미션 선언

<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

 

2. 위치권한 요청

//위치권한 요청
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    checkPermissions(permission);
}
//퍼미션 체크
@RequiresApi(api = Build.VERSION_CODES.M)
public void checkPermissions(String permissions) {

    int permissionCheck = ContextCompat.checkSelfPermission(this, permission);
    if (permissionCheck == PackageManager.PERMISSION_DENIED) {
        if (shouldShowRequestPermissionRationale("위치")) {
            //권한 설명 필요
            Toast.makeText(this, "블루투스 사용을 위해 권한이 필요합니다", Toast.LENGTH_SHORT).show();
        } else {
            requestPermissions(
                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                    REQUEST_CODE);
        }
    }
}

//안드로이드 퍼미션 요청결과
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions,
                                       int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    switch (requestCode) {
        case REQUEST_CODE:
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                //권한 승인
            } else {
                //권한 거부
                Toast.makeText(this, "위치 권한을 허용해주세요.", Toast.LENGTH_SHORT).show();
            }
            return;
    }
}

 

3. 블루투스 연결

//블루투스 연결
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
//블루투스가 켜져있을 때
if (bluetoothAdapter.getState() == BluetoothAdapter.STATE_ON) {
    bluetoothLeScanner = bluetoothAdapter.getBluetoothLeScanner();
    bluetoothLeScanner.startScan(scanCallback);
} else if (bluetoothAdapter == null || !bluetoothAdapter.isEnabled()) { 
//꺼져있을때
    Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
    startActivityForResult(intent, REQUEST_ENABLE_BT);
}
//스캔콜백
scanCallback = new ScanCallback() {
            @Override
            public void onScanResult(int callbackType, ScanResult result) {
                super.onScanResult(callbackType, result);

                if (result.getScanRecord().getDeviceName() == null) {
                //원하는 이름과 일치하는 디바이스가 없음
                    scanDeviceName = "Unknown";
                } else {
                    scanDeviceName = result.getScanRecord().getDeviceName();
                    Log.i("scanDeviceName", scanDeviceName);
                    if (scanDeviceName.equals(deviceName)) {
                    //원하는 이름과 일치하는 디바이스가 있을때 address 받아오기
                        scanDeviceAddress = result.getDevice().getAddress();
                        //스캔종료
                        bluetoothLeScanner.stopScan(scanCallback);
			//해당 주소로 연결
                        connection(scanDeviceAddress);
                    }
                }
            }
        };
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
public void connection(String scanDeviceAddress) {
    bluetoothDevice = bluetoothAdapter.getRemoteDevice(scanDeviceAddress);
    bluetoothGatt = bluetoothDevice.connectGatt(getApplicationContext(), false, bluetoothGattCallback);

}

 

+ Recent posts