본문 바로가기

Blog/Android

안드로이드 Bluetooth SPP

BluetoothSPP 

 

1. Manifest.xml 권한 등록

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

가장 먼저 블루투스를 이용하기 위해 권한을 등록해야 한다. 

BLUETOOTH : 블루투스 연결 요청, 연결 수락 및 데이터 전송과 같은 블루투스 통신 수행

BLUETOOTH_ADMIN : 블루투스 설정 조작 및 앱에서 기기 검색

 

2. gradle dependency에 bluetoothspp 추가

implementation 'com.akexorcist:bluetoothspp:1.0.0'

spp 라이브러리 이용

 

3. MainActivity에서 이용

// import
    import android.app.Activity;
    import android.bluetooth.BluetoothAdapter;
    import android.content.Intent;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.Button;
    import android.widget.Toast;

    import app.akexorcist.bluetotohspp.library.BluetoothSPP;
    import app.akexorcist.bluetotohspp.library.BluetoothState;
    import app.akexorcist.bluetotohspp.library.DeviceList;

    public class MainActivity extends AppCompatActivity {
    // import한 BluetoothSPP 변수 선언
    private BluetoothSPP bt;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 객체 생성 후 미리 선언한 변수에 넣음
        bt = new BluetoothSPP(this); //Initializing

        if (!bt.isBluetoothAvailable()) { //블루투스 사용 불가라면
            // 사용불가라고 토스트 띄워줌
            Toast.makeText(getApplicationContext()
            , "Bluetooth is not available"
            , Toast.LENGTH_SHORT).show();
            // 화면 종료
            finish();
        }

        // 데이터를 받았는지 감지하는 리스너
        bt.setOnDataReceivedListener(new BluetoothSPP.OnDataReceivedListener() { 
            //데이터 수신되면
            public void onDataReceived(byte[] data, String message) {
                Toast.makeText(MainActivity.this, message, Toast.LENGTH_SHORT).show(); // 토스트로 데이터 띄움
            }
        });
        // 블루투스가 잘 연결이 되었는지 감지하는 리스너
        bt.setBluetoothConnectionListener(new BluetoothSPP.BluetoothConnectionListener() { //연결됐을 때
            public void onDeviceConnected(String name, String address) {
                Toast.makeText(getApplicationContext()
                , "Connected to " + name + "\n" + address
                , Toast.LENGTH_SHORT).show();
            }

            public void onDeviceDisconnected() { //연결해제
                Toast.makeText(getApplicationContext()
                , "Connection lost", Toast.LENGTH_SHORT).show();
            }

            public void onDeviceConnectionFailed() { //연결실패
                Toast.makeText(getApplicationContext()
                , "Unable to connect", Toast.LENGTH_SHORT).show();
                }
            });
            // 연결하는 기능 버튼 가져와서 이용하기
            Button btnConnect = findViewById(R.id.btnConnect); //연결시도
            // 버튼 클릭하면
            btnConnect.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    if (bt.getServiceState() == BluetoothState.STATE_CONNECTED) { // 현재 버튼의 상태에 따라 연결이 되어있으면 끊고, 반대면 연결
                        bt.disconnect();
                    } else {
                        Intent intent = new Intent(getApplicationContext(), DeviceList.class);
                        startActivityForResult(intent, BluetoothState.REQUEST_CONNECT_DEVICE);
                    }
                }
            });
        }
        // 앱 중단시 (액티비티 나가거나, 특정 사유로 중단시)
        public void onDestroy() {
            super.onDestroy();
            bt.stopService(); //블루투스 중지
        }
        // 앱이 시작하면
        public void onStart() {
            super.onStart();
            if (!bt.isBluetoothEnabled()) { // 앱의 상태를 보고 블루투스 사용 가능하면
                Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                // 새로운 액티비티 띄워줌, 거기에 현재 가능한 블루투스 정보 intent로 넘겨
                startActivityForResult(intent, BluetoothState.REQUEST_ENABLE_BT); 
            } else {
                if (!bt.isServiceAvailable()) { // 블루투스 사용 불가
                    // setupService() 실행하도록 
                    bt.setupService();
                    bt.startService(BluetoothState.DEVICE_OTHER); //DEVICE_ANDROID는 안드로이드 기기끼리
                    // 셋팅 후 연결되면 setup()으로
                    setup();
                }
            }
        }
        // 블루투스 사용 - 데이터 전송
        public void setup() {
            Button btnSend = findViewById(R.id.btnSend); //데이터 전송
            btnSend.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    bt.send("Text", true);
                }
            });
        }
        // 새로운 액티비티 (현재 액티비티의 반환 액티비티?)
        public void onActivityResult(int requestCode, int resultCode, Intent data) {
            // 아까 응답의 코드에 따라 연결 가능한 디바이스와 연결 시도 후 ok 뜨면 데이터 전송
            if (requestCode == BluetoothState.REQUEST_CONNECT_DEVICE) { // 연결시도
                if (resultCode == Activity.RESULT_OK) // 연결됨
                    bt.connect(data);
                } else if (requestCode == BluetoothState.REQUEST_ENABLE_BT) { // 연결 가능
                    if (resultCode == Activity.RESULT_OK) { // 연결됨
                        bt.setupService();
                        bt.startService(BluetoothState.DEVICE_OTHER);
                        setup();
                } else { // 사용불가
                    Toast.makeText(getApplicationContext()
                    , "Bluetooth was not enabled."
                    , Toast.LENGTH_SHORT).show();
                    finish();
                }
            }
        }
    }

 

4. activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
	xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="space.codejun.btcommunicatoin.MainActivity">

	<Button
    android:id="@+id/btnConnect"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="연결"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

    <Button
    android:id="@+id/btnSend"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="8dp"
    android:text="보내기"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/btnConnect" />
</android.support.constraint.ConstraintLayout>

사실 액티비티는 버튼 연결이랑 보내기만 있어서 필요없지만, 혹시 모르니깐...



이렇게 블루투스 spp를 이용해 소켓 이용 대신 라이브러리로 쉽게 블루투스를 이용할 수 있다.

앱을 실행시키면 먼저 페어링 목록이 뜨며 밑에는 SCAN FOR DEVICES로 스캔할 수 있는 버튼도 있다.

디바이스를 클릭하면 연결이 되고 보내기 누르면 데이터가 보내진다.

현재 예제는 Text로 보내지지만 bt.send에 다른 문자열을 지정해 보낼 수 있다.

또한 뒤에 true와 false를 붙일 수 있는데, true를 하면 줄바꿈이 되어 보내지고 false를 하면 줄바꿈 없이 보내진다.<br>

 

참고 : 아두이노, 안드로이드 블루투스 통신하기