블루투스 검색응답 모드로 페어링 하기 (슬레이브 모드)
블루투스 활성화, 검색하기
+ 다른 블루투스 기기에서 내 휴대폰을 찾아 페어링하는 경우
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 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 | package com.ghj.bluetoothex; import android.app.Activity; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.database.DataSetObserver; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.view.ViewGroup; import android.widget.Adapter; import android.widget.Button; import android.widget.CheckBox; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.SimpleAdapter; import android.widget.TextView; import android.widget.Toast; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; public class MainActivity extends AppCompatActivity { //BluetoothAdapter BluetoothAdapter mBluetoothAdapter; //블루투스 요청 액티비티 코드 final static int BLUETOOTH_REQUEST_CODE = 100; //UI TextView txtState; Button btnSearch; CheckBox chkFindme; ListView listPaired; ListView listDevice; //Adapter SimpleAdapter adapterPaired; SimpleAdapter adapterDevice; //list - Device 목록 저장 List<Map<String,String>> dataPaired; List<Map<String,String>> dataDevice; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //UI txtState = (TextView)findViewById(R.id.txtState); chkFindme = (CheckBox)findViewById(R.id.chkFindme); btnSearch = (Button)findViewById(R.id.btnSearch); listPaired = (ListView)findViewById(R.id.listPaired); listDevice = (ListView)findViewById(R.id.listDevice); //Adapter1 dataPaired = new ArrayList<>(); adapterPaired = new SimpleAdapter(this, dataPaired, android.R.layout.simple_list_item_2, new String[]{"name","address"}, new int[]{android.R.id.text1, android.R.id.text2}); listPaired.setAdapter(adapterPaired); //Adapter2 dataDevice = new ArrayList<>(); adapterDevice = new SimpleAdapter(this, dataDevice, android.R.layout.simple_list_item_2, new String[]{"name","address"}, new int[]{android.R.id.text1, android.R.id.text2}); listDevice.setAdapter(adapterDevice); //블루투스 지원 유무 확인 mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); //블루투스를 지원하지 않으면 null을 리턴한다 if(mBluetoothAdapter == null){ Toast.makeText(this, "블루투스를 지원하지 않는 단말기 입니다.", Toast.LENGTH_SHORT).show(); finish(); return; } //블루투스 브로드캐스트 리시버 등록 //리시버1 IntentFilter stateFilter = new IntentFilter(); stateFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED); //BluetoothAdapter.ACTION_STATE_CHANGED : 블루투스 상태변화 액션 registerReceiver(mBluetoothStateReceiver, stateFilter); //리시버2 IntentFilter searchFilter = new IntentFilter(); searchFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED); //BluetoothAdapter.ACTION_DISCOVERY_STARTED : 블루투스 검색 시작 searchFilter.addAction(BluetoothDevice.ACTION_FOUND); //BluetoothDevice.ACTION_FOUND : 블루투스 디바이스 찾음 searchFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED); //BluetoothAdapter.ACTION_DISCOVERY_FINISHED : 블루투스 검색 종료 searchFilter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED); registerReceiver(mBluetoothSearchReceiver, searchFilter); //리시버3 IntentFilter scanmodeFilter = new IntentFilter(); scanmodeFilter.addAction(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED); registerReceiver(mBluetoothScanmodeReceiver, scanmodeFilter); //1. 블루투스가 꺼져있으면 활성화 // if(!mBluetoothAdapter.isEnabled()){ // mBluetoothAdapter.enable(); //강제 활성화 // } //2. 블루투스가 꺼져있으면 사용자에게 활성화 요청하기 if(!mBluetoothAdapter.isEnabled()){ Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(intent, BLUETOOTH_REQUEST_CODE); }else{ GetListPairedDevice(); } } //블루투스 상태변화 BroadcastReceiver BroadcastReceiver mBluetoothStateReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { //BluetoothAdapter.EXTRA_STATE : 블루투스의 현재상태 변화 int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, -1); //블루투스 활성화 if(state == BluetoothAdapter.STATE_ON){ txtState.setText("블루투스 활성화"); } //블루투스 활성화 중 else if(state == BluetoothAdapter.STATE_TURNING_ON){ txtState.setText("블루투스 활성화 중..."); } //블루투스 비활성화 else if(state == BluetoothAdapter.STATE_OFF){ txtState.setText("블루투스 비활성화"); } //블루투스 비활성화 중 else if(state == BluetoothAdapter.STATE_TURNING_OFF){ txtState.setText("블루투스 비활성화 중..."); } } }; //블루투스 검색결과 BroadcastReceiver BroadcastReceiver mBluetoothSearchReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); switch(action){ //블루투스 디바이스 검색 종료 case BluetoothAdapter.ACTION_DISCOVERY_STARTED: dataDevice.clear(); Toast.makeText(MainActivity.this, "블루투스 검색 시작", Toast.LENGTH_SHORT).show(); break; //블루투스 디바이스 찾음 case BluetoothDevice.ACTION_FOUND: //검색한 블루투스 디바이스의 객체를 구한다 BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); //데이터 저장 Map map = new HashMap(); map.put("name", device.getName()); //device.getName() : 블루투스 디바이스의 이름 map.put("address", device.getAddress()); //device.getAddress() : 블루투스 디바이스의 MAC 주소 dataDevice.add(map); //리스트 목록갱신 adapterDevice.notifyDataSetChanged(); break; //블루투스 디바이스 검색 종료 case BluetoothAdapter.ACTION_DISCOVERY_FINISHED: Toast.makeText(MainActivity.this, "블루투스 검색 종료", Toast.LENGTH_SHORT).show(); btnSearch.setEnabled(true); break; //블루투스 디바이스 페어링 상태 변화 case BluetoothDevice.ACTION_BOND_STATE_CHANGED: BluetoothDevice paired = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); if(paired.getBondState()==BluetoothDevice.BOND_BONDED){ //데이터 저장 Map map2 = new HashMap(); map2.put("name", paired.getName()); //device.getName() : 블루투스 디바이스의 이름 map2.put("address", paired.getAddress()); //device.getAddress() : 블루투스 디바이스의 MAC 주소 dataPaired.add(map2); //리스트 목록갱신 adapterPaired.notifyDataSetChanged(); } break; } } }; //블루투스 검색응답 모드 BroadcastReceiver BroadcastReceiver mBluetoothScanmodeReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { int state = intent.getIntExtra(BluetoothAdapter.EXTRA_SCAN_MODE, -1); switch (state){ case BluetoothAdapter.SCAN_MODE_CONNECTABLE: case BluetoothAdapter.SCAN_MODE_NONE: chkFindme.setChecked(false); chkFindme.setEnabled(true); Toast.makeText(MainActivity.this, "검색응답 모드 종료", Toast.LENGTH_SHORT).show(); break; case BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE: Toast.makeText(MainActivity.this, "다른 블루투스 기기에서 내 휴대폰을 찾을 수 있습니다.", Toast.LENGTH_SHORT).show(); break; } } }; //블루투스 검색 버튼 클릭 public void mOnBluetoothSearch(View v){ //검색버튼 비활성화 btnSearch.setEnabled(false); //mBluetoothAdapter.isDiscovering() : 블루투스 검색중인지 여부 확인 //mBluetoothAdapter.cancelDiscovery() : 블루투스 검색 취소 if(mBluetoothAdapter.isDiscovering()){ mBluetoothAdapter.cancelDiscovery(); } //mBluetoothAdapter.startDiscovery() : 블루투스 검색 시작 mBluetoothAdapter.startDiscovery(); } //검색응답 모드 - 블루투스가 외부 블루투스의 요청에 답변하는 슬레이브 상태 //BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE : 검색응답 모드 활성화 + 페이지 모드 활성화 //BluetoothAdapter.SCAN_MODE_CONNECTABLE : 검색응답 모드 비활성화 + 페이지 모드 활성화 //BluetoothAdapter.SCAN_MODE_NONE : 검색응답 모드 비활성화 + 페이지 모드 비활성화 //검색응답 체크박스 클릭 public void mOnChkFindme(View v){ //검색응답 체크 if(chkFindme.isChecked()){ if(mBluetoothAdapter.getScanMode() != BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE){ //검색응답 모드가 활성화이면 하지 않음 Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE); intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 60); //60초 동안 상대방이 나를 검색할 수 있도록한다 startActivity(intent); } } } //이미 페어링된 목록 가져오기 public void GetListPairedDevice(){ Set<BluetoothDevice> pairedDevice = mBluetoothAdapter.getBondedDevices(); dataPaired.clear(); if(pairedDevice.size() > 0){ for(BluetoothDevice device : pairedDevice){ //데이터 저장 Map map = new HashMap(); map.put("name", device.getName()); //device.getName() : 블루투스 디바이스의 이름 map.put("address", device.getAddress()); //device.getAddress() : 블루투스 디바이스의 MAC 주소 dataPaired.add(map); } } //리스트 목록갱신 adapterPaired.notifyDataSetChanged(); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { switch(requestCode){ case BLUETOOTH_REQUEST_CODE: //블루투스 활성화 승인 if(resultCode == Activity.RESULT_OK){ GetListPairedDevice(); } //블루투스 활성화 거절 else{ Toast.makeText(this, "블루투스를 활성화해야 합니다.", Toast.LENGTH_SHORT).show(); finish(); return; } break; } } @Override protected void onDestroy() { unregisterReceiver(mBluetoothStateReceiver); unregisterReceiver(mBluetoothSearchReceiver); super.onDestroy(); } } | cs |
activity_main
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 | <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:id="@+id/txtState" android:textSize="34dp" android:layout_width="match_parent" android:layout_height="wrap_content" /> <Button android:id="@+id/btnSearch" android:text="검색" android:textSize="34dp" android:layout_width="match_parent" android:layout_height="wrap_content" android:onClick="mOnBluetoothSearch"/> <TextView android:text="다른 블루투스 기기에서 내 휴대폰을 찾을 수 있도록 합니다." android:textSize="15dp" android:layout_width="match_parent" android:layout_height="wrap_content" /> <CheckBox android:id="@+id/chkFindme" android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="mOnChkFindme" /> <TextView android:text="페어링된 목록" android:layout_width="match_parent" android:layout_height="wrap_content" /> <ListView android:id="@+id/listPaired" android:layout_width="match_parent" android:layout_height="wrap_content" /> <TextView android:text="검색된 목록" android:layout_width="match_parent" android:layout_height="wrap_content" /> <ListView android:id="@+id/listDevice" android:layout_width="match_parent" android:layout_height="wrap_content"/> </LinearLayout> | cs |
AndroidManifest.xml
1 2 3 | <!-- 블루투스 권한 --> <uses-permission android:name="android.permission.BLUETOOTH" /> <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" /> | cs |
결과
처음에는 페어링된 디바이스가 없다
검색응답 모드로 변경한다(60초)
상대 단말기(마스터)에서 페어링요청을 한다
페어링하면 페어링된 목록에 추가된다
'IT > - 프로그래밍' 카테고리의 다른 글
안드로이드 MCC(Mobile Country Code) MNC(Mobile Network Code) 구하기 (0) | 2016.11.08 |
---|---|
안드로이드 블루투스 페어링 하기 (마스터 모드) (9) | 2016.11.06 |
안드로이드 블루투스 활성화, 검색하기 (1) | 2016.10.30 |
안드로이드 모델명, 제조사명, IMEI 정보 가져오기 (0) | 2016.08.31 |
안드로이드 화면 가로, 세로 구하기(pixcel, dpi, inch) (0) | 2016.08.29 |