본문 바로가기
안드로이드/개발자 일상

안드로이드 AltBeacon ( 비콘 연결 )

by 차누감 2020. 4. 19.

<실행 화면> 비콘을 연결했다가, 감지가 안되면 연결이 끊깁니다.

그리고 다시 신호 영역에 들어오면 자동적으로 연결이 됩니다.


우선 블루투스를 이용하기 위해선 권한이 필요합니다.

권한 요청을 쉽게 하기 위해 AutoPermissions 라이브러리를 사용하였습니다.

( AutoPermissions라이브러리 사용은 아래 링크를 확인하세요. )

2020/03/17 - [안드로이드/개발자 일상] - 안드로이드 앱 권한 요청 라이브러리 AutoPermissions

 

우선 AutoPermissions, AltBeacon 라이브러리를 추가합니다.

build.gradle

1
2
3
4
5
allprojects {
    repositories {
        maven { url 'https://jitpack.io' }
    }
}
1
2
3
4
implementation 'org.altbeacon:android-beacon-library:2+' // altbeacon
//noinspection GradleCompatible
implementation 'com.android.support:localbroadcastmanager:28.0.0'

 

앱 화면을 간단하게 만듭니다.

activity_main.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<?xml version="1.0" encoding="utf-8"?>
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
 
    <TextView
        android:id="@+id/tv_message"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Beacon"
        android:textSize="36sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
 
 
 

MainActivity에 implements BeaconConsumer, AutoPermissionsListener 합니다.

MainActivity.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
package com.example.ex_altbeacon;
 
 
 
 
 
 
 
public class MainActivity extends AppCompatActivity implements BeaconConsumer, AutoPermissionsListener {
 
    TextView textView;
 
    private BeaconManager beaconManager;
 
    String beaconUUID="AAC54CD6-EAAD-48D2-B060-AAAAAAAAE"// beacon -uuid
 
 
    private String TAG = "MainActivity";
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        textView=findViewById(R.id.tv_message);
 
        AutoPermissions.Companion.loadAllPermissions(this,101); // AutoPermissions
 
        beaconManager = BeaconManager.getInstanceForApplication(this);
        beaconManager.getBeaconParsers().add(new BeaconParser().setBeaconLayout("m:2-3=0215,i:4-19,i:20-21,i:22-23,p:24-24"));
        beaconManager.bind(this);
 
    }// onCreate()..
 
    @Override
    public void onBeaconServiceConnect() { beaconManager.removeAllMonitorNotifiers();
        beaconManager.setRangeNotifier(new RangeNotifier()
        {
            @Override
            public void didRangeBeaconsInRegion(Collection beacons, Region region)
            {
                if (beacons.size() > 0)
                {
                    Log.i(TAG, "The first beacon I see is about "+((Beacon)beacons.iterator().next()).getDistance()+" meters away.");
                }
            }
        });
        beaconManager.addMonitorNotifier(new MonitorNotifier() {
            @Override
            public void didEnterRegion(Region region) {
                Log.i(TAG, "I just saw an beacon for the first time!");
                Toast.makeText(MainActivity.this"didEnterRegion - 비콘 연결됨", Toast.LENGTH_SHORT).show();
                textView.setText("Beacon connected");
 
            }
 
            @Override
            public void didExitRegion(Region region) {
                Log.i(TAG, "I no longer see an beacon");
                Toast.makeText(MainActivity.this"didExitRegion - 비콘 연결 끊김", Toast.LENGTH_SHORT).show();
                textView.setText("Beacon disconnected");
            }
 
            @Override
            public void didDetermineStateForRegion(int state, Region region) {
                Log.i(TAG, "I have just switched from seeing/not seeing beacons: "+state);
            }
 
        });
 
        try {
            beaconManager.startMonitoringBeaconsInRegion(new Region("beacon"Identifier.parse(beaconUUID), nullnull));
        } catch (RemoteException e) {    }
        try
        {
            beaconManager.startRangingBeaconsInRegion(new Region("beacon"Identifier.parse(beaconUUID), nullnull));
        }
        catch (RemoteException e)
        {
        }
    }// onBeaconServiceConnect()..
 
 
    @Override
    public void onDestroy() {
        super.onDestroy();
        beaconManager.unbind(this);
    }
 
    @Override
    public void onDenied(int i, String[] strings) {
    }
 
    @Override
    public void onGranted(int i, String[] strings) {
    }
 
    @Override
    public void onPointerCaptureChanged(boolean hasCapture) {
    }
}// MainActivity class..
 
 

 

앱을 실행하기 전에 미리 블루투스를 켜놓고 합니다.

또는 블루투스 권한을 요청하는 코드를 추가하셔서 편하게 사용하셔도 됩니다.

 

<실행 화면> 비콘을 연결했다가, 감지가 안되면 연결이 끊깁니다.

그리고 다시 신호 영역에 들어오면 자동적으로 연결이 됩니다.

 

댓글