如何与HC-05和Android设备建立连接?

时间:2019-01-25 21:43:18

标签: android bluetooth null uuid

我正在创建一个应用程序,它将连接到蓝牙设备并发送数据。在第一个活动中,我正在搜索设备并进行配对,然后通过

发送已配对的设备

'intent.putExtra(“ blueDevice”,pairedDevice)'。

在下一个活动中,我正在收集设备地址和名称以创建连接。但是这里我有一个大问题,因为我不知道该怎么做。这是我后面活动的代码。

下面,我用两种不同的方法实现ConnectThread方法,哪一种是正确的?

不需要哪种方法?

public class RadioControl extends AppCompatActivity implements View.OnClickListener {

private BluetoothAdapter ba = BluetoothAdapter.getDefaultAdapter();
public BluetoothSocket mmSocket = null;
UUID uuid;
public static String uniqueID = null;
private static final String PREF_UNIQUE_ID = "PREF_UNIQUE_ID";
private BluetoothDevice blueDevice;
private final static UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");
int volume, frequency;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_radio_control);
    blueDevice = getIntent().getExtras().getParcelable("btDeviceInUse");
   // startCommunication(blueDevice);

    ConnectThread ct = new ConnectThread(blueDevice);
    ct.start();
}

@Override
protected void onResume() {
    super.onResume();
    //blueDevice = getIntent().getExtras().getParcelable("btDeviceInUse");
   // startCommunication(blueDevice);

    ConnectThread ct = new ConnectThread(blueDevice);
    ct.start();

     TextView rds_info, freq_info;
    Button vol_m, vol_p, freq_m, freq_p, scan_m, scan_p, rds_button;

    vol_p = findViewById(R.id.vol_p);
    vol_m = findViewById(R.id.vol_m);
    freq_p = findViewById(R.id.freq_p);
    freq_m = findViewById(R.id.freq_m);
    scan_p = findViewById(R.id.scan_p);
    scan_m = findViewById(R.id.scan_m);
    rds_button = findViewById(R.id.rds_func);
    rds_info = findViewById(R.id.RDS);
    //  freq_info = findViewById(R.id.freq_info);

    rds_info.setText(blueDevice.getName() + " \n" + blueDevice.getAddress());
    vol_p.setOnClickListener(this);
    vol_m.setOnClickListener(this);
    freq_p.setOnClickListener(this);
    freq_m.setOnClickListener(this);
    scan_p.setOnClickListener(this);
    scan_m.setOnClickListener(this);
    rds_button.setOnClickListener(this);

    //startCommunication(blueDevice);
}

@Override
public void onClick(View v) {
    ConnectThread ct = new ConnectThread(blueDevice);
    ct.start();
    switch (v.getId()) {

        case R.id.vol_m:

            volume = 50;
            try {
                //mmSocket = createBluetoothSocket(blueDevice);
             //   mmSocket.connect();
                mmSocket.getOutputStream().write(1);
            }
            catch (IOException e){
                break;
            }
            break;

        case R.id.vol_p:

            break;

        default:

            break;
    }

}

void startCommunication(BluetoothDevice device) {

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        ConnectThread mConnectThread = new ConnectThread(device);
        mConnectThread.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);

    } else {
        ConnectThread mConnectThread = new ConnectThread(device);
        mConnectThread.execute((Void) null);
    }

    //Toast.makeText(this, "Połączono", Toast.LENGTH_LONG).show();

}


public synchronized String id(Context context) {
    if (uniqueID == null) {
        SharedPreferences sharedPrefs = context.getSharedPreferences(
                PREF_UNIQUE_ID, Context.MODE_PRIVATE);
        uniqueID = sharedPrefs.getString(PREF_UNIQUE_ID, null);

        if (uniqueID == null) {
            uniqueID = UUID.randomUUID().toString();
            SharedPreferences.Editor editor = sharedPrefs.edit();
            editor.putString(PREF_UNIQUE_ID, uniqueID);
            //  editor.commit();
            editor.apply();
        }
    }

    return uniqueID;
}
private BluetoothSocket createBluetoothSocket(BluetoothDevice device)
        throws IOException {

        try {
            final Method m = device.getClass().getMethod("createInsecureRfcommSocketToServiceRecord", new Class[] { UUID.class });
            return (BluetoothSocket) m.invoke(device, uuid);
        } catch (Exception e) {
            Log.e("NOWEEEE", "Could not create Insecure RFComm Connection",e);
        }

    return  device.createRfcommSocketToServiceRecord(uuid);
}

public class ConnectThread extends AsyncTask<Void, Void, String> {

    private BluetoothDevice btDevice;
    boolean connectionState = true;
    private boolean isDeviceConnected = false;

    ConnectThread(BluetoothDevice device) {
        this.btDevice = device;
    }

    @Override
    protected String doInBackground(Void... params) {

        try {
            if (mmSocket == null || !isDeviceConnected) {

                BluetoothAdapter ba = BluetoothAdapter.getDefaultAdapter();
                ba.getRemoteDevice(btDevice.getAddress());
                mmSocket = btDevice.createRfcommSocketToServiceRecord(MY_UUID);
              Log.d("IDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD", "SOCKET CZY DZIALA" +  mmSocket.getConnectionType());
                ba.cancelDiscovery();
                mmSocket.connect();
            }

        } catch (Exception e) {
            isDeviceConnected = false;
            e.printStackTrace();
            return null;
        }

        return "";
    }


    @Override
    protected void onPostExecute(final String result) {

        // if (result != null){ Success }
        //  else { Connection Failed }
        super.onPostExecute(result);

        if (!connectionState) {
            Log.d("INFO_BT_STATUS_POLACZENIA", "Connection Failed. Is it a SPP Bluetooth? Try again.");
            // finish();
        } else {
            Log.d("INFO_BT_STATUS_POLACZENIA", "Connected.");
            isDeviceConnected = true;
        }
        //progress.dismiss();
    }


    @Override
    protected void onCancelled() {
    }

}


private class ConnectThread extends Thread {
    private final BluetoothDevice mmDevice;


    public ConnectThread(BluetoothDevice device) {
        BluetoothSocket tmp = null;
        mmDevice = device;

        try {
            tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
        } catch (IOException e) {}
        mmSocket  = tmp;
    }

    public void run () {
        ba.cancelDiscovery();

        try {
            mmSocket.connect();
        } catch (IOException connectException) {

            try {
                mmSocket.close();
            } catch (IOException closeException) {}
            return;
        }
        //manageConnectedSocket(mmSocket);
    }
    public void cancel() {
        try {
            mmSocket.close();
        } catch (IOException e) {}
    }
}

0 个答案:

没有答案