IT recording...

[Android] 안드로이드 블루투스(1) - Bluetooth on/off 본문

Android

[Android] 안드로이드 블루투스(1) - Bluetooth on/off

I-one 2020. 9. 9. 12:28

블루투스 포스팅은 다음과 같은 순서로 진행된다.

//1. Bluetooth on/off
//2. Discoverable / Find device
//3. Pairing device
//4. Send data

 

이 중 1. Bluetooth on/off를 알아보겠다. 

 

0. manifest 에 permission 을 추가한다.

(<manifest> 밑에 바로 넣으면 된다. )

<!--ble통신 권한-->
    <uses-permission android:name="android.permission.BLUETOOTH" />
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

 

1. activity_main.xml구성

(그림은 다른 버튼들 있는데, 코드는 ON/OFF만 넣어놓았다.)

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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=".MainActivity">

    <Button
        android:id="@+id/btnBluetoothOn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="30dp"
        android:layout_marginLeft="30dp"
        android:layout_marginTop="30dp"
        android:text="블루투스 ON"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/btnBluetoothOff"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginLeft="8dp"
        android:text="블루투스 OFF"
        app:layout_constraintStart_toEndOf="@+id/btnBluetoothOn"
        app:layout_constraintTop_toTopOf="@+id/btnBluetoothOn" />

    <TextView
        android:id="@+id/tvBluetoothStatus"
        android:layout_width="170dp"
        android:layout_height="20dp"
        android:layout_marginTop="10dp"
        android:text="status"
        app:layout_constraintStart_toStartOf="@+id/btnBluetoothOn"
        app:layout_constraintTop_toBottomOf="@+id/btnBluetoothOn" />



</androidx.constraintlayout.widget.ConstraintLayout>

2. main_activit.java에서 블루투스 on/off기능 

public class MainActivity extends AppCompatActivity {
    Button btnBluetoothOn;
    Button btnBluetoothOff;

    TextView tvBluetoothStatus;
    BluetoothAdapter mBluetoothAdapter;

    //Mode
    final static int BT_REQUEST_ENABLE = 1;
    final static int BT_MESSAGE_READ = 2;
    final static int BT_CONNECTING_STATUS = 3;

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

        //initialize
        btnBluetoothOn = findViewById(R.id.btnBluetoothOn);
        btnBluetoothOff = findViewById(R.id.btnBluetoothOff);
        tvBluetoothStatus = findViewById(R.id.tvBluetoothStatus);
       
        //get Defualt of blooth adapter
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

        //1. Bluetooth on/off
        btnBluetoothOn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                blueToothOn();
            }
        });

        btnBluetoothOff.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                blueToothOff();
            }
        });
    }

3. blueToothOn() 메소드 작성

public void blueToothOn() {
        if (mBluetoothAdapter == null) {
            Toast.makeText(getApplicationContext(), "This device doesn't support bluetooth service", Toast.LENGTH_SHORT).show();
            tvBluetoothStatus.setText("NonActive");
        } else if (mBluetoothAdapter.isEnabled()) {
            Toast.makeText(getApplicationContext(), "Already On", Toast.LENGTH_SHORT).show();
        } else {
            //Toast.makeText(getApplicationContext(), "Bluetooth On",Toast.LENGTH_SHORT).show();
            //Ask user
            Intent intentBluetoothEnable = new Intent(mBluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(intentBluetoothEnable, BT_REQUEST_ENABLE);//BT_REQUEST_ENABLE : ModeId

            //Intercept Status changed (by.broadcast)
            IntentFilter BTIntent = new IntentFilter(mBluetoothAdapter.ACTION_STATE_CHANGED);
            registerReceiver(mBroadCastReceiver, BTIntent);

        }
    }

3-1. mBluetoothAdapter가 null인지 검사한다. null이면 블루투스 지원하지 않는 기기

3-2. mBluetoothAdapter가 enable한지 검사한다. enable하면 이미 켜져있는 것

3-3. mBluetoothAdapter가 enable하지 않으면 이제 켜자

      Intent를 이용하여 ACTION_REQUEST_ENABLE을 불러 사용자에게 블루투스를 킬 것인지를 물어보는 창을 띄운다.

      startActivityForResult로 띄우기. (BT_REQUEST_ENABLE은 ID라고 생각하면된다)

3-4. IntentFilter는 블루투스에 관해 변경이 있을 경우 broadCastReceiver가 들어서 특정 행동을 취하게 하는 것을 말한다. (receiver는 밑에서 추가 작성한다.)

 

4. blueToothOff()메소드 작성

public void blueToothOff() {
        if (!mBluetoothAdapter.isEnabled()) {
            Toast.makeText(getApplicationContext(), "Already OFF", Toast.LENGTH_SHORT).show();
        } else if (mBluetoothAdapter.isEnabled()) {
            //Toast.makeText(getApplicationContext(), "Bluetooth Off",Toast.LENGTH_SHORT).show();
            mBluetoothAdapter.disable();
        }
    }

(설명생략)

 

5. BroadcastReceiver 작성

--안드로이드 개발자 사이트 참고

developer.android.com/guide/topics/connectivity/bluetooth#java

 

블루투스 개요  |  Android 개발자  |  Android Developers

The Android platform includes support for the Bluetooth network stack, which allows a device to wirelessly exchange data with other Bluetooth devices. The application framework provides access to the Bluetooth functionality through the Android Bluetooth…

developer.android.com

// Create a BroadcastReceiver
    private final BroadcastReceiver mBroadCastReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            if (action.equals(mBluetoothAdapter.ACTION_STATE_CHANGED)) {
                final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, mBluetoothAdapter.ERROR);

                switch (state) {
                    case BluetoothAdapter.STATE_ON:
                        Toast.makeText(getApplicationContext(), "Bluetooth On", Toast.LENGTH_SHORT).show();
                        tvBluetoothStatus.setText("Active");
                        break;
                    case BluetoothAdapter.STATE_OFF:
                        Toast.makeText(getApplicationContext(), "Bluetooth Off", Toast.LENGTH_SHORT).show();
                        tvBluetoothStatus.setText("NonActive");
                        break;
                    case BluetoothAdapter.STATE_TURNING_ON:
                        Toast.makeText(getApplicationContext(), "Bluetooth turning On", Toast.LENGTH_SHORT).show();
                        break;
                    case BluetoothAdapter.STATE_TURNING_OFF:
                        Toast.makeText(getApplicationContext(), "Bluetooth turning Off", Toast.LENGTH_SHORT).show();
                        break;
                }
            }//end if
        }//end onReceive
    };

receiver를 통해 받아온 action 을 비교한다. 

그 action 의 state가 on인지off인지, 켜지는중인지 꺼지는 중인지 구별하여 Toast메시지를 띄운다.

 

6. BroadcastReceiver 작성 시 onDestroy도 함께 써줘야한다.

protected void onDestroy() {
        Toast.makeText(getApplicationContext(), "onDestroy called", Toast.LENGTH_SHORT).show();
        Log.d("onDestroy", "onDestroy called");
        super.onDestroy();
        unregisterReceiver(mBroadCastReceiver);
    }
Comments