안녕하세요 초보 개발자입니다..
블루투스 기기를 검색하는 코드를 작성 중인데, 최초 실행시에는 잘 되다가 뒤로가기를 눌렀다 같은 동작(주변 기기 찾기)를 다시 수행하려면 에러가 나면서 앱이 종료됩니다. 왜일까요 ㅠㅠ
java 코드 전부 올립니다. 고수님들 도와주세요 ㅠㅠㅠㅠㅠ
++ 커스텀 액션 바에서 버튼 클릭 시 해당 버튼의 글자를 바꾸는 방법도 알 수 있을까요? .setText()로 하니까 안되더라구요 ;;;
public class Scanning extends AppCompatActivity{
static final int REQUEST_ENABLE_BT = 1;
ListView listView;
ArrayList<String> DeviceList;
BluetoothAdapter BTAdapter;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.scanning);
initListView(); //ListView 초기화
BTAdapter = BluetoothAdapter.getDefaultAdapter(); // Bluetooth Adapter 인스턴스 취득
if (BTAdapter == null) { // 블루투스 장비가 존재하지 않을 때
Toast toast = Toast.makeText(getApplicationContext(),
"Device not found", Toast.LENGTH_LONG);
toast.show();
} else {
if (!BTAdapter.isEnabled()) { //블루투스가 활성화 되어 있지 않을 때
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); // 블루투스를 활성화하는 인텐트 작성
startActivityForResult(intent, REQUEST_ENABLE_BT); // 시작
}
}
startFindDevice();
stopFindDevice();
}
public void onActivityResult(int requestCode, int resultCode, Intent data){
if(requestCode == REQUEST_ENABLE_BT){
if(resultCode == Activity.RESULT_OK){
Toast toast = Toast.makeText(getApplicationContext(), "Bluetooth is enabled now", Toast.LENGTH_SHORT);
toast.show();
}else {
Toast toast = Toast.makeText(getApplicationContext(), "Canceled", Toast.LENGTH_SHORT);
toast.show();
}
}
}
// 원격 디바이스 검색 시작
public void startFindDevice() {
// 디바이스 검색 시작
stopFindDevice();
BTAdapter.startDiscovery();
// 원격 디바이스 검색 이벤트 리시버 등록
registerReceiver(Recv, new IntentFilter(BluetoothDevice.ACTION_FOUND));
}
// 디바이스 검색 중지
protected void stopFindDevice() {
// 현재 디바이스 검색 중이라면 취소한다
if( BTAdapter.isDiscovering() ) {
BTAdapter.cancelDiscovery();
unregisterReceiver(Recv);
// 브로드캐스트 리시버를 등록 해제한다
}
}
// 원격 디바이스 검색 이벤트 수신
BroadcastReceiver Recv = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
if (intent.getAction() == BluetoothDevice.ACTION_FOUND) {
// 인텐트에서 디바이스 정보 추출
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// 디바이스를 목록에 추가
addDeviceToList(device.getName(), device.getAddress());
}
}
};
// 디바이스를 ListView 에 추가
public void addDeviceToList(String name, String address) {
// ListView 와 연결된 ArrayList 에 새로운 항목을 추가
String deviceInfo = name + " - " + address;
Log.d("tag1", "Device Found: " + deviceInfo);
DeviceList.add(deviceInfo);
// 화면을 갱신한다
ArrayAdapter adapter = (ArrayAdapter)listView.getAdapter();
adapter.notifyDataSetChanged();
}
// ListView 초기화
public void initListView() {
// 어댑터 생성
DeviceList = new ArrayList<String>();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, DeviceList);
// ListView 에 어댑터와 이벤트 리스너를 지정
listView = (ListView)findViewById(R.id.listView);
listView.setAdapter(adapter);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return super.onCreateOptionsMenu(menu); // 메뉴 고정
}
public boolean onOptionsItemSelected(MenuItem item) { // 메뉴 동작
switch (item.getItemId()) {
case R.id.bt_Scan:
startFindDevice();
break;
default:
return super.onOptionsItemSelected(item);
}
return true;
}
}