Computer >> 컴퓨터 >  >> 프로그래밍 >> Android

Android에서 현재 Bluetooth 주소를 가져오는 방법

개요

이 글에서는 Android 앱에서 현재 Bluetooth(블루투스) 주소, 즉 기기의 MAC 주소를 가져오는 방법을 단계별로 알아봅니다. BluetoothManager로 시스템 서비스에 접근한 뒤 BluetoothAdaptergetAddress() 메서드를 호출하는 것이 핵심입니다.

구현 단계

1단계: 새 프로젝트 생성

Android Studio에서 File → New Project 메뉴로 이동한 후, 필요한 항목을 모두 입력하여 새 프로젝트를 생성합니다.

2단계: 레이아웃 파일 작성

res/layout/activity_main.xml에 아래 코드를 추가합니다.

<?xml version = "1.0" encoding = "utf-8"?>
<LinearLayout xmlns:android = "https://schemas.android.com/apk/res/android"
   xmlns:app = "https://schemas.android.com/apk/res-auto"
   xmlns:tools = "https://schemas.android.com/tools"
   android:layout_width = "match_parent"
   android:gravity = "center"
   android:layout_height = "match_parent"
   tools:context = ".MainActivity">
   <TextView
      android:id = "@+id/text"
      android:textSize = "30sp"
      android:layout_width = "match_parent"
      android:layout_height = "match_parent" />
</LinearLayout>

위 코드에서는 블루투스 주소를 화면에 표시할 TextView 하나를 배치했으며, LinearLayout의 gravity 속성으로 내용을 중앙에 정렬했습니다.

3단계: MainActivity 코드 작성

src/MainActivity.java에 아래 코드를 추가합니다.

package com.example.myapplication;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.Network;
import android.os.Build;
import android.os.Bundle;
import android.os.health.SystemHealthManager;
import android.provider.Telephony;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.telephony.SmsManager;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
   TextView textView;
   @RequiresApi(api = Build.VERSION_CODES.N)
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      textView = findViewById(R.id.text);
      final BluetoothManager manager = (BluetoothManager) getSystemService(BLUETOOTH_SERVICE);
      textView.setText(manager.getAdapter().getAddress());
   }
   @Override
   protected void onStop() {
      super.onStop();
   }
   @Override
   protected void onResume() {
      super.onResume();
   }
}

핵심 로직은 다음과 같습니다. 먼저 getSystemService(BLUETOOTH_SERVICE)를 호출해 BluetoothManager 인스턴스를 얻고, 이어서 getAdapter().getAddress()로 현재 블루투스 어댑터의 주소를 가져와 TextView에 표시합니다.

4단계: 매니페스트 권한 설정

androidManifest.xml에 아래 코드를 추가합니다.

<?xml version = "1.0" encoding = "utf-8"?>
<manifest xmlns:android = "https://schemas.android.com/apk/res/android"
    package = "com.example.myapplication">
    <uses-permission android:name = "android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name = "android.permission.BLUETOOTH" />
    <uses-permission android:name = "android.permission.BLUETOOTH_ADMIN" />
    <application
       android:allowBackup = "true"
       android:icon = "@mipmap/ic_launcher"
       android:label = "@string/app_name"
       android:roundIcon = "@mipmap/ic_launcher_round"
       android:supportsRtl = "true"
       android:theme = "@style/AppTheme">
       <activity android:name = ".MainActivity">
          <intent-filter>
             <action android:name = "android.intent.action.MAIN" />
             <action android:name = "android.net.conn.CONNECTIVITY_CHANGE" />
             <category android:name = "android.intent.category.LAUNCHER" />
          </intent-filter>
       </activity>
    </application>
</manifest>

블루투스 기능을 사용하려면 BLUETOOTHBLUETOOTH_ADMIN 권한이 반드시 선언되어 있어야 합니다.

앱 실행 및 결과 확인

이제 애플리케이션을 실행해 보겠습니다. 실제 Android 기기가 컴퓨터에 연결되어 있다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 열고 툴바의 Run 아이콘을 클릭한 뒤, 목록에서 자신의 모바일 기기를 선택하세요. 그러면 기기 화면에 블루투스 주소가 표시됩니다.

Android에서 현재 Bluetooth 주소를 가져오는 방법

참고: Android 6.0 이상에서의 제한

Android 6.0(API 23)부터는 개인정보 보호를 위해 일반 서드파티 앱에서 getAddress()를 호출하면 실제 MAC 주소 대신 항상 02:00:00:00:00:00이라는 고정 값이 반환됩니다. 따라서 최신 Android 버전에서 실제 하드웨어 주소가 필요하다면 시스템 수준 권한을 활용하거나 다른 우회 방법을 고려해야 합니다.