IT recording...
[Android] 안드로이드 블루투스 (2) - Discoverable / Find device 본문
//1. Bluetooth on/off
//2. Discoverable / Find device
//3. Pairing device
//4. Send data
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" /> //이게 discover 권한
1. activity_main.xml 구성
(그냥 다른 기능 버튼들도 다 넣었다. 여기서는 이 세 버튼만 알면 된다.
<Button
android:id="@+id/btnDiscover"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="디바이스 찾기 허용"
app:layout_constraintStart_toStartOf="@+id/tvReceiveData"
app:layout_constraintTop_toBottomOf="@+id/tvReceiveData" />
<Button
android:id="@+id/btnFindDiscover"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="디바이스 찾기"
app:layout_constraintStart_toEndOf="@+id/btnDiscover"
app:layout_constraintTop_toTopOf="@+id/btnDiscover" />
<ListView
android:id="@+id/newDevicesList"
android:layout_width="match_parent"
android:layout_height="150dp"
app:layout_constraintStart_toStartOf="@+id/btnDiscover"
app:layout_constraintTop_toBottomOf="@+id/btnDiscover" />
--xml 전체코드
<?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" />
<Button
android:id="@+id/btnConnect"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_marginTop="10dp"
android:text="연결하기"
app:layout_constraintStart_toStartOf="@+id/tvBluetoothStatus"
app:layout_constraintTop_toBottomOf="@+id/tvBluetoothStatus" />
<TextView
android:id="@+id/tvReceiveData"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="Receive"
app:layout_constraintStart_toStartOf="@+id/btnSendData"
app:layout_constraintTop_toBottomOf="@+id/btnSendData" />
<Button
android:id="@+id/btnSendData"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="전송"
app:layout_constraintStart_toStartOf="@+id/btnConnect"
app:layout_constraintTop_toBottomOf="@+id/btnConnect" />
<EditText
android:id="@+id/tvSendData"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:ems="10"
android:inputType="textPersonName"
android:text="Send Data"
app:layout_constraintStart_toEndOf="@+id/btnSendData"
app:layout_constraintTop_toTopOf="@+id/btnSendData" />
<Button
android:id="@+id/btnDiscover"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="디바이스 찾기 허용"
app:layout_constraintStart_toStartOf="@+id/tvReceiveData"
app:layout_constraintTop_toBottomOf="@+id/tvReceiveData" />
<Button
android:id="@+id/btnFindDiscover"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="디바이스 찾기"
app:layout_constraintStart_toEndOf="@+id/btnDiscover"
app:layout_constraintTop_toTopOf="@+id/btnDiscover" />
<ListView
android:id="@+id/newDevicesList"
android:layout_width="match_parent"
android:layout_height="150dp"
app:layout_constraintStart_toStartOf="@+id/btnDiscover"
app:layout_constraintTop_toBottomOf="@+id/btnDiscover" />
</androidx.constraintlayout.widget.ConstraintLayout>
2. MainActivity.java에서 변수 초기화 / oncreate 부분 작성
activity_main.xml의 버튼들을 findViewById해서 연결해주고, onClickListener를 달았다.
public class MainActivity extends AppCompatActivity {
BluetoothAdapter mBluetoothAdapter;
Button btnDiscover;
public ArrayList<BluetoothDevice> mBTdevices;
public DeviceListAdapter mDeviceListAdapter;
ListView newDevicesList;
Button btnFindDiscover;
//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
btnDiscover = findViewById(R.id.btnDiscover);
btnFindDiscover = findViewById(R.id.btnFindDiscover);
newDevicesList = (ListView) findViewById(R.id.newDevicesList);
mBTdevices = new ArrayList<>();
//get Defualt of blooth adapter
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
btnDiscover.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
bluetoothDiscovery();
}
});
btnFindDiscover.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view) {
bluetoothDiscover();
}
});
}
3. bluetoothDiscovery() 메소드 작성
public void bluetoothDiscovery(){
Toast.makeText(getApplicationContext(), "Making device discoverable for 300 seconds.",Toast.LENGTH_SHORT).show();
Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,300);
startActivity(discoverableIntent);
//get scanmode change
IntentFilter intentFilter = new IntentFilter(mBluetoothAdapter.ACTION_SCAN_MODE_CHANGED);
registerReceiver(mBroadCastReceiver,intentFilter);
}
Intent를 이용하여 내 기기의 블루투스 검색을 허용하는 창을 띄운다. (ACTION_REQUEST_DISCOVERABLE)
IntentFilter를 등록하여 broadCastReceiver가 'scan mode가 change됐을 때' 알림을 받도록한다. ( 브로드캐스트 코드는 5번에서)
4. bluetoothDiscover() 메소드 작성
public void bluetoothDiscover(){
if(mBluetoothAdapter.isDiscovering()){ //already discovering > cancel
mBluetoothAdapter.cancelDiscovery();
Toast.makeText(getApplicationContext(), "Canceling discovery", Toast.LENGTH_SHORT).show();
checkBTPermissions(); //check for permissions
mBluetoothAdapter.startDiscovery();
IntentFilter discoverDevicesIntent = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mBroadCastReceiver,discoverDevicesIntent);
}
else if(!mBluetoothAdapter.isDiscovering()){
checkBTPermissions();
Toast.makeText(getApplicationContext(), "Starting discovery", Toast.LENGTH_SHORT).show();
mBluetoothAdapter.startDiscovery();
IntentFilter discoverDevicesIntent = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mBroadCastReceiver,discoverDevicesIntent);
}
}
이미 찾는 중이라면 cancel 후 startDiscovery(), 아니라면 바로 startDiscovery()를 수행한다.
IntentFilter를 등록하여 broadCastReceiver가 'action 이 found됐을 때 ' 알림을 받도록한다. ( 브로드캐스트 코드는 5번에서)
**checkBTPermissions()는 사용자에게 블루투스를 검색 할 것인지 권한을 묻는 기능을 한다. 이를 작성하지 않을 시에는 intentfilter를 달았더라도 ACTION_FOUND에 대해 broadCastReceiver가 말을 듣지 않으니 반드시 작성해야 한다.
(위에서 checkBTPermissions();에 빨간 줄이 뜨는 것은 버전때문이나 빌드에는 이상이 없으므로 무시하면 된다.)
@RequiresApi(api = Build.VERSION_CODES.M)
private void checkBTPermissions(){
if(Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP){
int permissionCheck = this.checkSelfPermission("Manifest.permission.ACCESS_FINE_LOCATION");
permissionCheck += this.checkSelfPermission("Manifest.permission.ACCESS_FINE_LOCATION");
if(permissionCheck!=0){
this.requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.ACCESS_COARSE_LOCATION},1001);
}
else{
Log.d("checkPermission", "No need to check permissions. SDK version < LoLLIPOP");
}
}
}
(관련글)
it-recording.tistory.com/15?category=923966
5. broadCastReceiver()
// 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_SCAN_MODE_CHANGED)) {
final int mode = intent.getIntExtra(BluetoothAdapter.EXTRA_SCAN_MODE, BluetoothAdapter.ERROR);
switch (mode) {
case BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE:
Toast.makeText(getApplicationContext(), "Discoverability enabled", Toast.LENGTH_SHORT).show();
break;
case BluetoothAdapter.SCAN_MODE_CONNECTABLE:
Toast.makeText(getApplicationContext(), "Discoverability Disabled. Able to receive connections", Toast.LENGTH_SHORT).show();
break;
case BluetoothAdapter.SCAN_MODE_NONE:
Toast.makeText(getApplicationContext(), "Discoverability Disabled. Not able to receive connections", Toast.LENGTH_SHORT).show();
break;
case BluetoothAdapter.STATE_CONNECTING:
Toast.makeText(getApplicationContext(), "Connecting...", Toast.LENGTH_SHORT).show();
break;
case BluetoothAdapter.STATE_CONNECTED:
Toast.makeText(getApplicationContext(), "Connected.",Toast.LENGTH_SHORT).show();
break;
}
}//end else if
else if(action.equals(BluetoothDevice.ACTION_FOUND)){
//get devices
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
mBTdevices.add(device);
Toast.makeText(getApplicationContext(), device.getName()+" : "+device.getAddress(), Toast.LENGTH_SHORT).show();
//attach device to adapter & set list
mDeviceListAdapter = new DeviceListAdapter(context,R.layout.device_adapter_view, mBTdevices);
newDevicesList.setAdapter(mDeviceListAdapter);
}//end else if
}//end onReceive
};
3번과 4번에서 등록한 intenfilter 값을 들을 receiver를 작성한다.
각각 ACTION_SCAN_MODE_CHANGED ( 내 기기의 블루투스 스캔이 가능한지 상태)
, ACTION_FOUND (다른 기기를 찾았는지)
- 다른 기기를 찾았을 때 그 기기를 mBTdevices 라는 bluetoothDevice를 저장하는 arrayList에 add하고,
화면에 나타내기 위해 DeviceListAdapter 클래스를 추가 작성하여 구성한다. (7번)
+ onDestroy() 작성하기 (broadCastReceiver사용시 반드시 할 것)
@Override
protected void onDestroy() {
Toast.makeText(getApplicationContext(), "onDestroy called", Toast.LENGTH_SHORT).show();
Log.d("onDestroy", "onDestroy called");
super.onDestroy();
unregisterReceiver(mBroadCastReceiver);
}
6. device_adapter_view.xml 구성
찾은 기기의 name과 address를 보여줄 리스트의 xml을 구성한다.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:id="@+id/tvDeviceName"
android:textSize="15sp"/>
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:id="@+id/tvDeviceAddress"
android:textSize="15sp"/>
</LinearLayout>
7. DeviceListAdapter.java
찾은 기기를 device_adapter_view를 이용하여 화면에 띄운다.
package com.example.ble_train;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import java.util.ArrayList;
import java.util.List;
public class DeviceListAdapter extends ArrayAdapter<BluetoothDevice> {
private LayoutInflater mLayoutInflater;
private ArrayList<BluetoothDevice> mDevices;
private int mViewResourceId;
public DeviceListAdapter(Context context, int resourceId, ArrayList<BluetoothDevice> devices) {
super(context, resourceId, devices);
this.mDevices = devices;
mLayoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mViewResourceId = resourceId;
}
public View getView(int position , View convertView, ViewGroup parent){
convertView = mLayoutInflater.inflate(mViewResourceId,null);
BluetoothDevice device = mDevices.get(position);
if(device!=null){
TextView deviceName = (TextView) convertView.findViewById(R.id.tvDeviceName);
TextView deviceAddress = (TextView) convertView.findViewById(R.id.tvDeviceAddress);
//원래 null검사 해야하는데 검색되는 것중 null인게 있어서 뺌
//if(deviceName !=null){
deviceName.setText(device.getName());
//}
//else if(deviceAddress!=null){
deviceAddress.setText(device.getAddress());
//}
}
return convertView;
}
}
--결과
디바이스 찾기를 누르면 다음과 같이 list가 뜬다.
(이름이 없는 것은 null인 것. )
=== MainActivity.java 전체 코드
package com.example.ble_train;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.icu.util.Output;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import org.w3c.dom.Text;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.UUID;
//1. Bluetooth on/off
//2. Discoverable / Find device
//3. Pairing device
//4. Send data
public class MainActivity extends AppCompatActivity {
Button btnBluetoothOn;
Button btnBluetoothOff;
TextView tvBluetoothStatus;
Button btnConnect;
BluetoothAdapter mBluetoothAdapter;
Button btnDiscover;
public ArrayList<BluetoothDevice> mBTdevices;
public DeviceListAdapter mDeviceListAdapter;
ListView newDevicesList;
Button btnFindDiscover;
//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);
btnConnect = findViewById(R.id.btnConnect);
btnDiscover = findViewById(R.id.btnDiscover);
btnFindDiscover = findViewById(R.id.btnFindDiscover);
newDevicesList = (ListView) findViewById(R.id.newDevicesList);
mBTdevices = new ArrayList<>();
//get Defualt of blooth adapter | get Permitted(Manifest)
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();
}
});
btnDiscover.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
bluetoothDiscovery();
}
});
btnFindDiscover.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view) {
bluetoothDiscover();
}
});
}
@RequiresApi(api = Build.VERSION_CODES.M)
private void checkBTPermissions(){
if(Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP){
int permissionCheck = this.checkSelfPermission("Manifest.permission.ACCESS_FINE_LOCATION");
permissionCheck += this.checkSelfPermission("Manifest.permission.ACCESS_FINE_LOCATION");
if(permissionCheck!=0){
this.requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.ACCESS_COARSE_LOCATION},1001);
}
else{
Log.d("checkPermission", "No need to check permissions. SDK version < LoLLIPOP");
}
}
}
// 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
else if (action.equals(mBluetoothAdapter.ACTION_SCAN_MODE_CHANGED)) {
final int mode = intent.getIntExtra(BluetoothAdapter.EXTRA_SCAN_MODE, BluetoothAdapter.ERROR);
switch (mode) {
case BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE:
Toast.makeText(getApplicationContext(), "Discoverability enabled", Toast.LENGTH_SHORT).show();
break;
case BluetoothAdapter.SCAN_MODE_CONNECTABLE:
Toast.makeText(getApplicationContext(), "Discoverability Disabled. Able to receive connections", Toast.LENGTH_SHORT).show();
break;
case BluetoothAdapter.SCAN_MODE_NONE:
Toast.makeText(getApplicationContext(), "Discoverability Disabled. Not able to receive connections", Toast.LENGTH_SHORT).show();
break;
case BluetoothAdapter.STATE_CONNECTING:
Toast.makeText(getApplicationContext(), "Connecting...", Toast.LENGTH_SHORT).show();
break;
case BluetoothAdapter.STATE_CONNECTED:
Toast.makeText(getApplicationContext(), "Connected.",Toast.LENGTH_SHORT).show();
break;
}
}//end else if
else if(action.equals(BluetoothDevice.ACTION_FOUND)){
//get devices
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
mBTdevices.add(device);
Toast.makeText(getApplicationContext(), device.getName()+" : "+device.getAddress(), Toast.LENGTH_SHORT).show();
//attach device to adapter & set list
mDeviceListAdapter = new DeviceListAdapter(context,R.layout.device_adapter_view, mBTdevices);
newDevicesList.setAdapter(mDeviceListAdapter);
}//end else if
}//end onReceive
};
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);
}
}
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();
}
}
public void bluetoothDiscovery(){
Toast.makeText(getApplicationContext(), "Making device discoverable for 300 seconds.",Toast.LENGTH_SHORT).show();
Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,300);
startActivity(discoverableIntent);
//get scanmode change
IntentFilter intentFilter = new IntentFilter(mBluetoothAdapter.ACTION_SCAN_MODE_CHANGED);
registerReceiver(mBroadCastReceiver,intentFilter);
}
public void bluetoothDiscover(){
if(mBluetoothAdapter.isDiscovering()){ //already discovering > cancel
mBluetoothAdapter.cancelDiscovery();
Toast.makeText(getApplicationContext(), "Canceling discovery", Toast.LENGTH_SHORT).show();
checkBTPermissions(); //check for permissions
mBluetoothAdapter.startDiscovery();
IntentFilter discoverDevicesIntent = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mBroadCastReceiver,discoverDevicesIntent);
}
else if(!mBluetoothAdapter.isDiscovering()){
checkBTPermissions();
Toast.makeText(getApplicationContext(), "Starting discovery", Toast.LENGTH_SHORT).show();
mBluetoothAdapter.startDiscovery();
IntentFilter discoverDevicesIntent = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mBroadCastReceiver,discoverDevicesIntent);
}
}
@Override
protected void onDestroy() {
Toast.makeText(getApplicationContext(), "onDestroy called", Toast.LENGTH_SHORT).show();
Log.d("onDestroy", "onDestroy called");
super.onDestroy();
unregisterReceiver(mBroadCastReceiver);
}
}
'Android' 카테고리의 다른 글
[Android] Fragment NullException 오류 해결방법 (0) | 2020.09.21 |
---|---|
[Android] values/strings.xml 에서 다른 xml 파일 참조하고 싶을때 (0) | 2020.09.14 |
[Android] 안드로이드 블루투스(1) - Bluetooth on/off (0) | 2020.09.09 |
[Android] BluetoothDevice.ACTION_FOUND / 블루투스 디바이스 찾기 해도 BroadcastReceiver에 들어가지 않는 오류 (0) | 2020.09.09 |
[Android] BLE (블루투스 통신) (0) | 2020.09.08 |