Не удаётся создать приём и отправку данных через Bluetooth
Уже долгое время застрял на 1 моменте, не удаётся создать приём и отправку данных. Не понимаю, в чём дело, перепробовал несколько вариантов кодов, но не получилается. Прошу помощи.
MainActivity:
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private BluetoothAdapter BluetoothAdapter;
private StringBuilder sb = new StringBuilder();
private ListView listView;
public static String ventilator_str;
public static String nagrevatel_str;
public static String pompa_str;
public static String auto_str;
Handler h;
private ConnectedThread myThread;
private final int ReciveData = 1;
private TextView myPrintReciveBuffer;
public static BluetoothSocket clientSocket;
private static final UUID myUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
private static String address = "21:13:01:80:20"; //Вместо “00:00” Нужно нудет ввести MAC нашего bluetooth
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Check();
Button SearchSrart = (Button) findViewById(R.id.StartSearch);
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter != null) {
// С Bluetooth все в порядке.
}
SearchSrart.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//если разрешения получены (функция ниже)
if (permissionGranted()) {
//адаптер для управления блютузом
BluetoothAdapter = android.bluetooth.BluetoothAdapter.getDefaultAdapter();
if (bluetoothEnabled()) { //если блютуз включен (функция ниже)
findArduino(); //начать поиск устройства (функция ниже)
}
}
}
});
h = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case ReciveData:
byte[] readbuff = (byte[]) msg.obj;
String strInComm = new String(readbuff, 0, msg.arg1);
myPrintReciveBuffer.setText(myPrintReciveBuffer.getText() + strInComm);
break;
}
}
};
}
private boolean permissionGranted() {
//если оба разрешения получены, вернуть true
if (ContextCompat.checkSelfPermission(getApplicationContext(),
Manifest.permission.BLUETOOTH) == PermissionChecker.PERMISSION_GRANTED &&
ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.BLUETOOTH_ADMIN) == PermissionChecker.PERMISSION_GRANTED) {
return true;
} else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.BLUETOOTH,
Manifest.permission.BLUETOOTH_ADMIN}, 0);
return false;
}
}
private void findArduino() //функция для выбора устройства из списка доступных для подключения
{
Set<BluetoothDevice> pairedDevices = BluetoothAdapter.getBondedDevices();
if (pairedDevices.size() > 0) {
listView = findViewById(R.id.Arraylist);
List<BluetoothDevice> data = new ArrayList<>(pairedDevices);
ListAdapter adapter = new ListAdapter(data, getApplicationContext());
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
BluetoothDevice device = (BluetoothDevice) adapterView.getItemAtPosition(position);
device.getAddress();
int i = 1;
String itemMAC = listView.getItemAtPosition(i).toString().split("/", 2)[0];
BluetoothDevice connectDevice = BluetoothAdapter.getRemoteDevice(itemMAC);
try {
//генерируем socket - поток, через который будут посылаться данные
Method m = connectDevice.getClass().getMethod(
"createRfcommSocket", new Class[]{int.class});
clientSocket = (BluetoothSocket) m.invoke(connectDevice, 1);
clientSocket.connect();
if (clientSocket.isConnected()) {
//если соединение установлено, завершаем поиск
BluetoothAdapter.cancelDiscovery();
}
} catch (Exception e) {
e.getStackTrace();
}
}
});
}
}
private boolean bluetoothEnabled() {
//если блютуз включен, вернуть true, если нет, вежливо попросить пользователя его включить
if (BluetoothAdapter.isEnabled()) {
return true;
} else {
Intent enableBtIntent = new Intent(android.bluetooth.BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 0);
return false;
}
}
private static class ThreadConnectBTdevice extends Thread { // Поток для коннекта с Bluetooth
private OutputStream outputStream = null;
private BluetoothSocket bluetoothSocket = null;
private ThreadConnectBTdevice(BluetoothDevice device) {
try {
bluetoothSocket = device.createRfcommSocketToServiceRecord(myUUID);
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static class ListAdapter extends ArrayAdapter<BluetoothDevice> implements View.OnClickListener {
private Context mContext;
public static class ViewHolder {
TextView tvName;
}
public ListAdapter(List<BluetoothDevice> data, Context context) {
super(context, R.layout.row_item, data);
ArrayList<BluetoothDevice> dataSet = (ArrayList<BluetoothDevice>) data;
this.mContext = context;
}
@Override
public void onClick(View view) {
int position = (Integer) view.getTag();
Object object = getItem(position);
BluetoothDevice dataModel = (BluetoothDevice) object;
switch (view.getId()) {
case R.id.name:
Toast.makeText(mContext, "Name" + Objects.requireNonNull(dataModel).getName(), Toast.LENGTH_SHORT).show();
break;
}
}
private int lastPosition = -1;
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
// Get the data item for this position
BluetoothDevice dataModel = getItem(position);
// Check if an existing view is being reused, otherwise inflate the view
ViewHolder viewHolder; // view lookup cache stored in tag
final View result;
if (convertView == null) {
viewHolder = new ViewHolder();
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(R.layout.row_item, parent, false);
viewHolder.tvName = convertView.findViewById(R.id.name);
result = convertView;
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
result = convertView;
}
Animation animation = AnimationUtils.loadAnimation(mContext, (position > lastPosition) ? R.anim.up_from_bottom : R.anim.down_from_top);
result.startAnimation(animation);
lastPosition = position;
viewHolder.tvName.setText(Objects.requireNonNull(dataModel).getName());
// Return the completed view to render on screen
return convertView;
}
}
public void Check() {
Switch ventil_switch = (Switch) findViewById(R.id.switch_ventilator);
final Switch nagrev_switch = (Switch) findViewById(R.id.switch_nagrev);
final Switch pompa_switch = (Switch) findViewById(R.id.switch_pompa);
Switch auto_switch = (Switch) findViewById(R.id.switch_auto);
ventil_switch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
System.out.println("Включен вентилятор");
int ventilator = 1;
String ventilator_str = Integer.toString(ventilator);
String OtpravkaVentil = ("/" + ventilator_str + "/" + nagrevatel_str + "/" + pompa_str + "/" + auto_str + "/");
System.out.println(OtpravkaVentil);
Log.d(TAG, "...Посылаем данные: " + OtpravkaVentil + "...");
} else {
System.out.println("Выключен вентилятор");
int ventilator = 0;
String ventilator_str = Integer.toString(ventilator);
String OtpravkaVentil = ("/" + ventilator_str + "/" + nagrevatel_str + "/" + pompa_str + "/" + auto_str + "/");
System.out.println(OtpravkaVentil);
Log.d(TAG, "...Посылаем данные: " + OtpravkaVentil + "...");
}
}
});
nagrev_switch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
System.out.println("Включен нагреватель");
int nagrevatel = 1;
String nagrevatel_str = Integer.toString(nagrevatel);
String OtpravkaNagrev = ("/" + ventilator_str + "/" + nagrevatel_str + "/" + pompa_str + "/" + auto_str + "/");
System.out.println(OtpravkaNagrev);
Log.d(TAG, "...Посылаем данные: " + OtpravkaNagrev + "...");
} else {
System.out.println("Выключен нагреватель");
int nagrevatel = 0;
String nagrevatel_str = Integer.toString(nagrevatel);
String OtpravkaNagrev = ("/" + ventilator_str + "/" + nagrevatel_str + "/" + pompa_str + "/" + auto_str + "/");
System.out.println(OtpravkaNagrev);
Log.d(TAG, "...Посылаем данные: " + OtpravkaNagrev + "...");
}
}
});
pompa_switch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
System.out.println("Включена помпа");
int pompa = 1;
String pompa_str = Integer.toString(pompa);
String PompaOtpravka = ("/" + ventilator_str + "/" + nagrevatel_str + "/" + pompa_str + "/" + auto_str + "/");
Log.d(TAG, "...Посылаем данные: " + PompaOtpravka + "...");
} else {
System.out.println("Выключена помпа");
int pompa = 0;
String pompa_str = Integer.toString(pompa);
String PompaOtpravka = ("/" + ventilator_str + "/" + nagrevatel_str + "/" + pompa_str + "/" + auto_str + "/");
Log.d(TAG, "...Посылаем данные: " + PompaOtpravka + "...");
}
}
});
auto_switch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
System.out.println("Включен автоматический режим");
int auto = 1;
String auto_str = Integer.toString(auto);
String AutoOtpravka = ("/" + ventilator_str + "/" + nagrevatel_str + "/" + pompa_str + "/" + auto_str + "/");
System.out.println(AutoOtpravka);
myThread.sendData();
Log.d(TAG, "...Посылаем данные: " + AutoOtpravka + "...");
} else {
System.out.println("Выключен автоматический режим");
int auto = 0;
String auto_str = Integer.toString(auto);
String AutoOtpravka = ("/" + ventilator_str + "/" + nagrevatel_str + "/" + pompa_str + "/" + auto_str + "/");
System.out.println(AutoOtpravka);
Log.d(TAG, "...Посылаем данные: " + AutoOtpravka + "...");
}
System.out.println(ventilator_str + "это проверка, если null, то пиздец");
}
});
}
private class ConnectedThread extends Thread {
private BluetoothSocket genBtSocket;
private OutputStream genOutStream;
private InputStream genInStream;
public ConnectedThread(BluetoothSocket socket) {
genBtSocket = socket;
OutputStream tmpOut = null;
InputStream tmpIn = null;
try {
tmpOut = socket.getOutputStream();
tmpIn = socket.getInputStream();
} catch (IOException e) {
}
genOutStream = tmpOut;
genInStream = tmpIn;
}
public void run() {
byte[] buffer = new byte[16];
int bytes;
while (true) {
try {
bytes = genInStream.read(buffer);
h.obtainMessage(ReciveData, bytes, -1, buffer).sendToTarget();
} catch (IOException e) {
break;
}
}
}
public void sendData(){
String str = "Hello!";
byte[] msgBuffer = str.getBytes();
try{
genOutStream.write(msgBuffer);
} catch (IOException e) {Toast.makeText(getApplicationContext(),"не вышло",Toast.LENGTH_SHORT).show();}
}
}
}
Буду благодарен за любую помощь.