package com.example.bluetoothtest;
import android.Manifest;
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.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
BluetoothAdapter bluetoothAdapter;
static int BLUETOOTH_REQUEST_CODE = 100;
int MY_PERMISSIONS_REQUEST_ACCESS_COARSE_LOCATION = 1;
TextView txtState;
Button btnSearch;
ListView listDevice;
SimpleAdapter adapterDevice;
List<Map<String, String>> dataDevice;
@Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtState = (TextView)findViewById(R.id.txtState);
btnSearch = (Button)findViewById(R.id.btnSearch);
listDevice = (ListView)findViewById(R.id.listDevice);
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, MY_PERMISSIONS_REQUEST_ACCESS_COARSE_LOCATION);
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);
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if(bluetoothAdapter == null){
Toast.makeText(this, "블루투스를 지원하지 않는 단말기입니다.", Toast.LENGTH_LONG).show();
finish();
} else if(!bluetoothAdapter.isEnabled()){
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(intent, BLUETOOTH_REQUEST_CODE);
}
IntentFilter stateFilter = new IntentFilter();
stateFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
registerReceiver(mBluetoothStateReceiver, stateFilter);
IntentFilter searchFilter = new IntentFilter();
searchFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
searchFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
searchFilter.addAction(BluetoothDevice.ACTION_FOUND);
registerReceiver(mBluetoothSearchReceiver, searchFilter);
btnSearch.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
btnSearch.setEnabled(false);
if(bluetoothAdapter.isDiscovering()){
bluetoothAdapter.cancelDiscovery();
}
onDestroy();
}
});
}
BroadcastReceiver mBluetoothStateReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, -1);
switch (state) {
case BluetoothAdapter.STATE_ON: //디바이스 상태 온
Log.d("스태이트온", String.valueOf(BluetoothAdapter.STATE_ON));
txtState.setText("블루투스 활성화");
break;
case BluetoothAdapter.STATE_TURNING_ON: //디바이스가 활성화되고있음
Log.d("스태이트 터닝온 ", String.valueOf(BluetoothAdapter.STATE_TURNING_ON));
txtState.setText("블루투스 활성화 중.....");
break;
case BluetoothAdapter.STATE_OFF: //디바이스 비활성화
Log.d("스테이트 오프", String.valueOf(BluetoothAdapter.STATE_OFF));
txtState.setText("블루투스 비활성화");
break;
case BluetoothAdapter.STATE_TURNING_OFF: //디바이스 비활성화 되고있음.
Log.d("스테이트 터닝 오프", String.valueOf(BluetoothAdapter.STATE_TURNING_OFF));
txtState.setText("블루투스 비활성화 중.....");
break;
}
}
};
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(getApplicationContext(), "블루투스 검색 시작", Toast.LENGTH_LONG).show();
Log.d("액션_DISCOVERY_STARTED :", BluetoothAdapter.ACTION_DISCOVERY_STARTED);
break;
case BluetoothDevice.ACTION_FOUND :
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
Log.d("액션_FOUND :", BluetoothDevice.ACTION_FOUND);
Map map = new HashMap();
map.put("name", device.getName());
map.put("address", device.getAddress());
dataDevice.add(map);
adapterDevice.notifyDataSetChanged();
break;
case BluetoothAdapter.ACTION_DISCOVERY_FINISHED:
Log.d("액션_DISCOVERY_FINISHED :", BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
Toast.makeText(getApplicationContext(), "블루투스 검색 종료", Toast.LENGTH_LONG).show();
btnSearch.setEnabled(true);
break;
}
}
};
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == BLUETOOTH_REQUEST_CODE) {
if (resultCode == Activity.RESULT_OK) { //블루투스 페어링 성공
} else {
Toast.makeText(getApplicationContext(), "블루투스 사용 거부.", Toast.LENGTH_SHORT); //페어링이 실패하면 블루투스 사용거부 메세지 출력
finish();
}
}
}
public void onDiscovery(View view){
bluetoothAdapter.startDiscovery();
}
@Override
protected void onDestroy() {
unregisterReceiver(mBluetoothStateReceiver); //브로드캐스트 연결 종료
unregisterReceiver(mBluetoothSearchReceiver); // 브로드캐스트 연결 종료
super.onDestroy();
}
@Override
protected void onResume() { //액티비티가 다시 재개되었을때
super.onResume();
}
@Override
protected void onPause() {
super.onPause();
}
}
처음에 핸드폰에서 블루투스를 꺼놔야
블루투스를 킬것이냐는 묻는거 나온뒤에 확인을 하면
자동으로 searchFilter가 동작합니다..ㅠㅠ
그리고는 ACTION_DISCOVERY_FINISHED 얘만 동작해요
ACTION_DISCOVERY_STARTED, ACTION_FOUND 이게 동작을 안해서
리스트뷰에 블루투스 목록이 안나오는것 같습니다.
그후 검색 버튼을 눌러도 또다시 searchFilter가 동작을 안해요
로그에는 startDiscovery 이것만 찍히고 아무동작이 없네요..ㅜ
검색버튼을 누르면 searchFilter가 동작을 안하니 다시 검색버튼이 활성화도 안되구요..
블루투스를 켜놓으면 stateFilter도 동작을 안하구요(뭐 켜놓았으니 안되는것이라 생각이 듭니다.)
searchFilter도 동작을 안합니다..ㅠㅠ 이유가 뭘까요