У меня проблема с моим приложением Android: у меня есть два списка (устройств), которые отображаются в двух элементах listView (один за другим) - список найденных устройств, которые еще не сопряжены, и список сопряженных устройств.
1) Когда я нажимаю на устройство, к которому я хочу подключиться, оно должно быть помещено во второй список, и первый список должен быть обновлен. Но в настоящее время сопряженное устройство отображается в списках ОБА.
Где проблема?
public class MainMenu extends AppCompatActivity implements View.OnClickListener {
private BluetoothAdapter ba;
private BluetoothDevice selectedDevice;
private ArrayAdapter<String> foundDevicesAdapter, pairAdapter;
private ArrayList<String> foundDevicesList = new ArrayList<>();
private ArrayList<String> pairedList = new ArrayList<>();
private ArrayList<String> allUUIDList = new ArrayList<>();
// private ArrayList<String> pairedDeivicesUUIDList = new ArrayList<>();
// private ArrayList<String> unpairedDevicesUUIDList = new ArrayList<>();
private ArrayList<BluetoothDevice> pairedDevicesList = null;
private ArrayList<BluetoothDevice> arrayListBluetoothDevicesReadyToPair = null;
private ArrayList<BluetoothDevice> listOfAllDevices = new ArrayList<>();
private IntentFilter filter = new IntentFilter();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_menu);
ListView viewListOfDevices, viewListOfPairedDevices;
int MY_PERMISSIONS_REQUEST_ACCESS_COARSE_LOCATION = 1;
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
MY_PERMISSIONS_REQUEST_ACCESS_COARSE_LOCATION);
viewListOfDevices = findViewById(R.id.btDevicesList);
viewListOfPairedDevices = findViewById(R.id.btPairedDevicesList);
Button searchButton = findViewById(R.id.searchButton);
searchButton.setOnClickListener(this);
ba = BluetoothAdapter.getDefaultAdapter();
filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
filter.addAction(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(btReceiver, filter);
arrayListBluetoothDevicesReadyToPair = new ArrayList<>();
pairedDevicesList = new ArrayList<>();
foundDevicesAdapter = new ArrayAdapter<>(getApplicationContext(), R.layout.row_item, R.id.deviceName, foundDevicesList); //ArrayAdapter<String>
pairAdapter = new ArrayAdapter<>(getApplicationContext(), R.layout.row_item, R.id.deviceName, pairedList);
viewListOfDevices.setAdapter(foundDevicesAdapter);
viewListOfPairedDevices.setAdapter(pairAdapter);
viewListOfDevices.setOnItemClickListener(foundListener);
viewListOfPairedDevices.setOnItemClickListener(pairedListener);
foundDevicesAdapter.notifyDataSetChanged();
pairAdapter.notifyDataSetChanged();
} // onCreate
public void showDialog(String title, CharSequence message, final BluetoothDevice selectedDevice, final int position) { // zamiast Context context bylo Activity activity -> Context jest pochodna od Activity
final Context context = MainMenu.this;
AlertDialog.Builder dialogBox = new AlertDialog.Builder(context);
if (title != null) dialogBox.setTitle(title);
dialogBox.setMessage(message);
dialogBox.setPositiveButton("Połącz", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
Toast.makeText(context, "Łączę z urządzeniem " + selectedDevice.getName() + "..", Toast.LENGTH_LONG).show();
}
});
dialogBox.setNegativeButton("Usuń", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
pairAdapter.clear(); // to czyszczenie nic nie dalo
foundDevicesAdapter.clear();
pairAdapter.notifyDataSetChanged();
foundDevicesAdapter.notifyDataSetChanged();
try {
Boolean removeBonding = removeBond(selectedDevice);
if (removeBonding && selectedDevice.getBondState() == BluetoothDevice.BOND_NONE) {
pairedDevicesList.remove(position);
pairedList.remove(position);
searchBtDevices();
}
Log.i("Log", "Removed: " + removeBonding);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
dialogBox.show();// -> ta byla pierwsza
}
AdapterView.OnItemClickListener foundListener = new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapter, View v, int position, long id) {
if (!arrayListBluetoothDevicesReadyToPair.isEmpty()) {
selectedDevice = arrayListBluetoothDevicesReadyToPair.get(position);
Boolean isBonded;
ba.cancelDiscovery();
try {
isBonded = createBond(selectedDevice);
if (isBonded && selectedDevice.getBondState() == BluetoothDevice.BOND_BONDED) {
arrayListBluetoothDevicesReadyToPair.remove(position);
foundDevicesList.remove(position);
foundDevicesAdapter.notifyDataSetChanged();
pairedDevicesList.add(selectedDevice);
pairedList.add(selectedDevice.getAddress() + ", " + selectedDevice.getName());
pairAdapter.notifyDataSetChanged();
}
} catch (Exception e) {
e.printStackTrace();
}
}
pairAdapter.clear(); // doesn't work, the list is doubled after clicking device
foundDevicesAdapter.clear();
pairAdapter.notifyDataSetChanged();
foundDevicesAdapter.notifyDataSetChanged();
// searchBtDevices();
}
};// ClickedListItem
AdapterView.OnItemClickListener pairedListener = new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (!pairedDevicesList.isEmpty()) {
selectedDevice = pairedDevicesList.get(position);
showDialog("Wybierz opcję", "Wybrano sparowane urządzenie Bluetooth." +
"Połączyć czy usunąć?", selectedDevice, position);
}
}
};// ClickOnPairedDevice
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.searchButton:
if (!ba.isDiscovering()) {
pairAdapter.clear();
foundDevicesAdapter.clear();
checkBtAdapterEnabled(ba);
searchBtDevices();
pairAdapter.notifyDataSetChanged();
foundDevicesAdapter.notifyDataSetChanged();
//Toast.makeText(this, "Zakonczono wyszukiwanie.", Toast.LENGTH_SHORT).show();
}
else if (ba.isDiscovering()) Toast.makeText(this, "Szukam...", Toast.LENGTH_SHORT).show();
break;
}
}// onClick
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent i) {
if (resultCode == Activity.RESULT_OK) {
Log.d("INFO_OK", "Wlaczony BT");
ba = BluetoothAdapter.getDefaultAdapter();
}
}
private void checkBtAdapterEnabled(BluetoothAdapter ba) {
if (!ba.isEnabled()) {
Intent i = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(i, 1);
}
}// checkBtAdapterEnabled()
private final BroadcastReceiver btReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
Boolean flag = true;
//Parcelable uuidExtra = intent.getParcelableExtra(BluetoothDevice.EXTRA_UUID);
// Parcelable[] uuidExtra = intent.getParcelableArrayExtra(BluetoothDevice.EXTRA_UUID);
// ParcelUuid[] deviceUuids = device.getUuids();
// if (listOfAllDevices != null) {
for (BluetoothDevice listOfAllDevice : listOfAllDevices) {
if (device.getAddress().equals(listOfAllDevice.getAddress()) && device.getName().equals(listOfAllDevice.getName())) {
flag = false;
}
}
// }
//if (flag && uuidExtra != null) {
if (flag) {
listOfAllDevices.add(device);
}
} else if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
Log.e("bluetoothReceiver", "ACTION_DISCOVERY_STARTED");
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
if (!listOfAllDevices.isEmpty()) {
for (BluetoothDevice fetchedDevice : listOfAllDevices) {
if (fetchedDevice.getBondState() != BluetoothDevice.BOND_BONDED) {
arrayListBluetoothDevicesReadyToPair.add(fetchedDevice);
// unpairedDevicesUUIDList.add(allUUIDList.get(i));
foundDevicesList.add(fetchedDevice.getName() + ", " + fetchedDevice.getAddress());
foundDevicesAdapter.notifyDataSetChanged();
} else {
pairedDevicesList.add(fetchedDevice);
// pairedDeivicesUUIDList.add(allUUIDList.get(i));
pairedList.add(fetchedDevice.getName() + ", " + fetchedDevice.getAddress());
pairAdapter.notifyDataSetChanged();
}
}
}
Log.e("bluetoothReceiver", "ACTION_DISCOVERY_FINISHED");
for (int i = 0; i < listOfAllDevices.size(); i++) {
Log.d("LISTA URZADZEN", "LISTA URZADZEN ZNALEZIONYCH: " + listOfAllDevices.get(i).getName());
}
}
}// onReceive()
};
private void searchBtDevices() {
Log.d("INFO_SZUKAM", "SZUKAM URZADZEN");
// IntentFilter filter = new IntentFilter(); //BluetoothDevice.ACTION_FOUND); // poszlo do globala
filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
filter.addAction(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
this.registerReceiver(btReceiver, filter);
ba.startDiscovery();
while (ba.isDiscovering()) Toast.makeText(this, "Szukam...", Toast.LENGTH_SHORT).show();
//if(ba.getState().equals(BluetoothAdapter.ACTION_DISCOVERY_FINISHED.toString())) Toast.makeText(this, "Zakonczono wyszukiwanie.", Toast.LENGTH_SHORT).show();
}// searchDevicesBT()
@Override
protected void onResume() {
super.onResume();
checkBtAdapterEnabled(ba);
this.registerReceiver(btReceiver, filter);
}
@Override
protected void onStart() {
super.onStart();
checkBtAdapterEnabled(ba);
this.registerReceiver(btReceiver, filter);
}
@Override
protected void onPause() {
super.onPause();
if (ba != null) {
ba.cancelDiscovery();
}
this.unregisterReceiver(btReceiver);
}//onDestroy()
@Override
protected void onDestroy() {
super.onDestroy();
if (ba != null) {
ba.cancelDiscovery();
}
try {
this.unregisterReceiver(btReceiver);
} catch (Exception e) {
e.printStackTrace();
}
}//onDestroy()
private boolean createBond(BluetoothDevice btDevice) throws Exception {
Class bondClass = Class.forName("android.bluetooth.BluetoothDevice");
Method createBondMethod = bondClass.getMethod("createBond");
return (Boolean) createBondMethod.invoke(btDevice);
}//createBond()
private boolean removeBond(BluetoothDevice btDevice) throws Exception {
Class btClass = Class.forName("android.bluetooth.BluetoothDevice");
Method removeBondMethod = btClass.getMethod("removeBond");
return (Boolean) removeBondMethod.invoke(btDevice);
}// removeBond()
}//MainMenu
У меня также проблема с методом onDestroy. После минимизации ошибки приложения появляется сообщение «java.lang.IllegalArgumentException: получатель не зарегистрирован» (onDestroy).