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

안드로이드에서 현재 블루투스 이름 가져오는 방법 – 단계별 코드 예제

이 예제는 Android에서 현재 블루투스(Bluetooth) 이름을 가져오는 방법을 보여줍니다. BluetoothManager를 통해 어댑터를 얻은 뒤 getName() 메서드를 호출하면 간단하게 구현할 수 있습니다.

구현 단계

1단계 − 새 프로젝트 생성

Android Studio에서 File ⇒ New Project로 이동하여 새 프로젝트를 생성하고, 필요한 모든 세부 정보를 입력합니다.

2단계 − activity_main.xml 수정

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를 배치했습니다.

3단계 − MainActivity.java 작성

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().getName());
   }
   @Override
   protected void onStop() {
      super.onStop();
   }
   @Override
   protected void onResume() {
      super.onResume();
   }
}

위 코드에서는 getSystemService(BLUETOOTH_SERVICE)BluetoothManager 인스턴스를 얻은 후, getAdapter().getName()을 호출해 현재 기기의 블루투스 이름을 가져와 TextView에 출력합니다.

4단계 − AndroidManifest.xml 설정

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>

블루투스 기능을 사용하려면 매니페스트에 BLUETOOTH 권한과 BLUETOOTH_ADMIN 권한이 반드시 선언되어야 합니다. 참고로 Android 12(API 31) 이상을 대상하는 경우에는 BLUETOOTH_CONNECT 권한도 함께 요청해야 할 수 있습니다.

실행 결과 확인

이제 애플리케이션을 실행해 보겠습니다. 실제 Android 휴대폰이 컴퓨터에 연결되어 있다고 가정합니다. Android Studio에서 프로젝트의 액티비티 파일 중 하나를 연 뒤 도구 모음의 Run 아이콘을 클릭하고, 실행할 모바일 기기를 선택합니다. 그러면 기기 화면에 현재 블루투스 이름이 표시됩니다.

안드로이드에서 현재 블루투스 이름 가져오는 방법 – 단계별 코드 예제