蓝牙连接

时间:2018-02-17 16:19:20

标签: android bluetooth arduino

我在不同的论坛上看了很多关于这方面的话题,似乎没有人帮助我。

我最近买了一个与Arduino IDE兼容的Elegoo车载套件,它附带了不同类型的代码,而不是。他们甚至拥有自己的Android应用程序。

我的问题是我想创建自己的Android蓝牙应用程序,它连接/与模块配对,可以远程控制汽车。我启动并运行了我的应用程序,它可以扫描附近的设备,HC-08模块出现在列表中,但我无法连接。当我尝试连接它说它无法与HC-08通信。我很确定问题出在android端,因为如果elegoo板上有任何代码,elegoo蓝牙应用程序根本不会与蓝牙模块连接。蓝牙模块是HC-08。

有人可以帮我吗?

此外,我正在关注这个youtube教程,所以他可以获得代码。 https://www.youtube.com/watch?v=YJ0JQXcNNTA

以下是主要活动代码:

 public class MainActivity extends AppCompatActivity implements 
 AdapterView.OnItemClickListener{
private static final String TAG = "MainActivity";

BluetoothAdapter mBluetoothAdapter;
Button btnEnableDisable_Discoverable;

public ArrayList<BluetoothDevice> mBTDevices = new ArrayList<>();

public DeviceListAdapter mDeviceListAdapter;

ListView lvNewDevices;


// Create a BroadcastReceiver for ACTION_FOUND
private final BroadcastReceiver mBroadcastReceiver1 = new BroadcastReceiver() {
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        // When discovery finds a device
        if (action.equals(mBluetoothAdapter.ACTION_STATE_CHANGED)) {
            final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, mBluetoothAdapter.ERROR);

            switch(state){
                case BluetoothAdapter.STATE_OFF:
                    Log.d(TAG, "onReceive: STATE OFF");
                    break;
                case BluetoothAdapter.STATE_TURNING_OFF:
                    Log.d(TAG, "mBroadcastReceiver1: STATE TURNING OFF");
                    break;
                case BluetoothAdapter.STATE_ON:
                    Log.d(TAG, "mBroadcastReceiver1: STATE ON");
                    break;
                case BluetoothAdapter.STATE_TURNING_ON:
                    Log.d(TAG, "mBroadcastReceiver1: STATE TURNING ON");
                    break;
            }
        }
    }
};

/**
 * Broadcast Receiver for changes made to bluetooth states such as:
 * 1) Discoverability mode on/off or expire.
 */
private final BroadcastReceiver mBroadcastReceiver2 = new BroadcastReceiver() {

    @Override
    public void onReceive(Context context, Intent intent) {
        final String action = intent.getAction();

        if (action.equals(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED)) {

            int mode = intent.getIntExtra(BluetoothAdapter.EXTRA_SCAN_MODE, BluetoothAdapter.ERROR);

            switch (mode) {
                //Device is in Discoverable Mode
                case BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE:
                    Log.d(TAG, "mBroadcastReceiver2: Discoverability Enabled.");
                    break;
                //Device not in discoverable mode
                case BluetoothAdapter.SCAN_MODE_CONNECTABLE:
                    Log.d(TAG, "mBroadcastReceiver2: Discoverability Disabled. Able to receive connections.");
                    break;
                case BluetoothAdapter.SCAN_MODE_NONE:
                    Log.d(TAG, "mBroadcastReceiver2: Discoverability Disabled. Not able to receive connections.");
                    break;
                case BluetoothAdapter.STATE_CONNECTING:
                    Log.d(TAG, "mBroadcastReceiver2: Connecting....");
                    break;
                case BluetoothAdapter.STATE_CONNECTED:
                    Log.d(TAG, "mBroadcastReceiver2: Connected.");
                    break;
            }

        }
    }
};




/**
 * Broadcast Receiver for listing devices that are not yet paired
 * -Executed by btnDiscover() method.
 */
private BroadcastReceiver mBroadcastReceiver3 = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        final String action = intent.getAction();
        Log.d(TAG, "onReceive: ACTION FOUND.");

        if (action.equals(BluetoothDevice.ACTION_FOUND)){
            BluetoothDevice device = intent.getParcelableExtra (BluetoothDevice.EXTRA_DEVICE);
            mBTDevices.add(device);
            Log.d(TAG, "onReceive: " + device.getName() + ": " + device.getAddress());
            mDeviceListAdapter = new DeviceListAdapter(context, R.layout.device_adapter_view, mBTDevices);
            lvNewDevices.setAdapter(mDeviceListAdapter);
        }
    }
};

/**
 * Broadcast Receiver that detects bond state changes (Pairing status changes)
 */
private final BroadcastReceiver mBroadcastReceiver4 = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        final String action = intent.getAction();

        if(action.equals(BluetoothDevice.ACTION_BOND_STATE_CHANGED)){
            BluetoothDevice mDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            //3 cases:
            //case1: bonded already
            if (mDevice.getBondState() == BluetoothDevice.BOND_BONDED){
                Log.d(TAG, "BroadcastReceiver: BOND_BONDED.");
            }
            //case2: creating a bone
            if (mDevice.getBondState() == BluetoothDevice.BOND_BONDING) {
                Log.d(TAG, "BroadcastReceiver: BOND_BONDING.");
            }
            //case3: breaking a bond
            if (mDevice.getBondState() == BluetoothDevice.BOND_NONE) {
                Log.d(TAG, "BroadcastReceiver: BOND_NONE.");
            }
        }
    }
};



@Override
protected void onDestroy() {
    Log.d(TAG, "onDestroy: called.");
    super.onDestroy();
    unregisterReceiver(mBroadcastReceiver1);
    unregisterReceiver(mBroadcastReceiver2);
    unregisterReceiver(mBroadcastReceiver3);
    unregisterReceiver(mBroadcastReceiver4);
    //mBluetoothAdapter.cancelDiscovery();
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Button btnONOFF = (Button) findViewById(R.id.btnONOFF);
    btnEnableDisable_Discoverable = (Button) findViewById(R.id.btnDiscoverable_on_off);
    lvNewDevices = (ListView) findViewById(R.id.lvNewDevices);
    mBTDevices = new ArrayList<>();

    //Broadcasts when bond state changes (ie:pairing)
    IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
    registerReceiver(mBroadcastReceiver4, filter);

    mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

    lvNewDevices.setOnItemClickListener(MainActivity.this);


    btnONOFF.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Log.d(TAG, "onClick: enabling/disabling bluetooth.");
            enableDisableBT();
        }
    });

}



public void enableDisableBT(){
    if(mBluetoothAdapter == null){
        Log.d(TAG, "enableDisableBT: Does not have BT capabilities.");
    }
    if(!mBluetoothAdapter.isEnabled()){
        Log.d(TAG, "enableDisableBT: enabling BT.");
        Intent enableBTIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivity(enableBTIntent);

        IntentFilter BTIntent = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
        registerReceiver(mBroadcastReceiver1, BTIntent);
    }
    if(mBluetoothAdapter.isEnabled()){
        Log.d(TAG, "enableDisableBT: disabling BT.");
        mBluetoothAdapter.disable();

        IntentFilter BTIntent = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
        registerReceiver(mBroadcastReceiver1, BTIntent);
    }

}


public void btnEnableDisable_Discoverable(View view) {
    Log.d(TAG, "btnEnableDisable_Discoverable: Making device discoverable for 300 seconds.");

    Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
    discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
    startActivity(discoverableIntent);

    IntentFilter intentFilter = new IntentFilter(mBluetoothAdapter.ACTION_SCAN_MODE_CHANGED);
    registerReceiver(mBroadcastReceiver2,intentFilter);

}

public void btnDiscover(View view) {
    Log.d(TAG, "btnDiscover: Looking for unpaired devices.");

    if(mBluetoothAdapter.isDiscovering()){
        mBluetoothAdapter.cancelDiscovery();
        Log.d(TAG, "btnDiscover: Canceling discovery.");

        //check BT permissions in manifest
        checkBTPermissions();

        mBluetoothAdapter.startDiscovery();
        IntentFilter discoverDevicesIntent = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        registerReceiver(mBroadcastReceiver3, discoverDevicesIntent);
    }
    if(!mBluetoothAdapter.isDiscovering()){

        //check BT permissions in manifest
        checkBTPermissions();

        mBluetoothAdapter.startDiscovery();
        IntentFilter discoverDevicesIntent = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        registerReceiver(mBroadcastReceiver3, discoverDevicesIntent);
    }
}

/**
 * This method is required for all devices running API23+
 * Android must programmatically check the permissions for bluetooth. Putting the proper permissions
 * in the manifest is not enough.
 *
 * NOTE: This will only execute on versions > LOLLIPOP because it is not needed otherwise.
 */
private void checkBTPermissions() {
    if(Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP){
        int permissionCheck = this.checkSelfPermission("Manifest.permission.ACCESS_FINE_LOCATION");
        permissionCheck += this.checkSelfPermission("Manifest.permission.ACCESS_COARSE_LOCATION");
        if (permissionCheck != 0) {

            this.requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 1001); //Any number
        }
    }else{
        Log.d(TAG, "checkBTPermissions: No need to check permissions. SDK version < LOLLIPOP.");
    }
}

@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
    //first cancel discovery because its very memory intensive.
    mBluetoothAdapter.cancelDiscovery();

    Log.d(TAG, "onItemClick: You Clicked on a device.");
    String deviceName = mBTDevices.get(i).getName();
    String deviceAddress = mBTDevices.get(i).getAddress();

    Log.d(TAG, "onItemClick: deviceName = " + deviceName);
    Log.d(TAG, "onItemClick: deviceAddress = " + deviceAddress);

    //create the bond.
    //NOTE: Requires API 17+? I think this is JellyBean
    if(Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN_MR2){
        Log.d(TAG, "Trying to pair with " + deviceName);
        mBTDevices.get(i).createBond();
    }
    }
    }

///这也是我的DeviceListAdapter代码:

public class DeviceListAdapter extends ArrayAdapter<BluetoothDevice> {

private LayoutInflater mLayoutInflater;
private ArrayList<BluetoothDevice> mDevices;
private int  mViewResourceId;

public DeviceListAdapter(Context context, int tvResourceId, ArrayList<BluetoothDevice> devices){
    super(context, tvResourceId,devices);
    this.mDevices = devices;
    mLayoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    mViewResourceId = tvResourceId;
}

public View getView(int position, View convertView, ViewGroup parent) {
    convertView = mLayoutInflater.inflate(mViewResourceId, null);

    BluetoothDevice device = mDevices.get(position);

    if (device != null) {
        TextView deviceName = (TextView) convertView.findViewById(R.id.tvDeviceName);
        TextView deviceAdress = (TextView) convertView.findViewById(R.id.tvDeviceAddress);

        if (deviceName != null) {
            deviceName.setText(device.getName());
        }
        if (deviceAdress != null) {
            deviceAdress.setText(device.getAddress());
        }
    }

    return convertView;
}

}

1 个答案:

答案 0 :(得分:0)

有关蓝牙的一些教程已经很老了!我上周刚刚进行了Arduino-Android蓝牙通信工作,所以这应该适合你!首先在清单文件中添加以下权限:

<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

然后在你的主要使用它。

公共类MainActivity扩展了AppCompatActivity {

private final String DEVICE_ADDRESS="benamekhoda"; //I actually used Device Name instead of address 
private final UUID PORT_UUID = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb"); //Serial Port Service UUID
private BluetoothDevice device; //Our Bluetooth Device
private BluetoothSocket socket;
private OutputStream outputStream;
private InputStream inputStream;
Button startButton, sendButton,clearButton,stopButton;
TextView textView;
EditText editText;
boolean deviceConnected=false;
Thread thread;
byte buffer[];
int bufferPosition;
boolean stopThread;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    editText = (EditText) findViewById(R.id.edittext);
    textView = (TextView) findViewById(R.id.textview);
    startButton = (Button) findViewById(R.id.buttonStart);
    startButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if(BTinit())
            {
                if(BTconnect())
                {
                    setUiEnabled(true);
                    deviceConnected=true;
                    beginListenForData();
                    textView.append("\nConnection Opened!\n");
                }
                else{
                    Toast.makeText(getApplicationContext(),"BTconnect false",Toast.LENGTH_SHORT).show();
                }

            }
            else{
                Toast.makeText(getApplicationContext(),"BTinit false",Toast.LENGTH_SHORT).show();
            }
        }
    });
    sendButton = (Button) findViewById(R.id.buttonSend);
    sendButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            String string = editText.getText().toString();
            string.concat("\n");
            try {
                outputStream.write(string.getBytes());
            } catch (IOException e) {
                e.printStackTrace();
            }
            textView.append("\nSent Data:"+string+"\n");
        }
    });
    clearButton = (Button) findViewById(R.id.buttonClear);
    clearButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            onClickClear(view);
        }
    });
    stopButton = (Button) findViewById(R.id.buttonStop);
    stopButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            onClickSend(view);
        }
    });

    setUiEnabled(false);
}
public void setUiEnabled(boolean bool)
{
    startButton.setEnabled(!bool);
    sendButton.setEnabled(bool);
    stopButton.setEnabled(bool);
    textView.setEnabled(bool);
}

public boolean BTinit()
{
    boolean found=false;
    BluetoothAdapter bluetoothAdapter=BluetoothAdapter.getDefaultAdapter();
    if (bluetoothAdapter == null) {
        Toast.makeText(getApplicationContext(),"Device doesnt Support Bluetooth",Toast.LENGTH_SHORT).show();
    }
    if(!bluetoothAdapter.isEnabled())
    {
        Intent enableAdapter = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(enableAdapter, 0);
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    Set<BluetoothDevice> bondedDevices = bluetoothAdapter.getBondedDevices(); //Something like ArrayList but no duplicate is allowed and data is unordered
    if(bondedDevices.isEmpty())
    {
        Toast.makeText(getApplicationContext(),"Please Pair the Device first",Toast.LENGTH_SHORT).show();
    }
    else
    {
        for (BluetoothDevice iterator : bondedDevices)
        {
            if(iterator.getName().equals(DEVICE_ADDRESS))
            {
                device=iterator;
                Toast.makeText(getApplicationContext(),"found the device",Toast.LENGTH_SHORT).show();
                found=true;
                break;
            }
        }
    }
    return found;
}

public boolean BTconnect()
{
    boolean connected=true;
    try {

        socket = device.createRfcommSocketToServiceRecord(PORT_UUID);
        socket.connect();
    } catch (IOException e) {
        e.printStackTrace();
        Toast.makeText(getApplicationContext(),"throw1",Toast.LENGTH_SHORT).show();
        connected=false;
    }
    if(connected)
    {
        try {
            outputStream=socket.getOutputStream();
        } catch (IOException e) {
            e.printStackTrace();
            Toast.makeText(getApplicationContext(),"throw2",Toast.LENGTH_SHORT).show();
        }
        try {
            inputStream=socket.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
            Toast.makeText(getApplicationContext(),"throw3",Toast.LENGTH_SHORT).show();
        }

    }


    return connected;
}



void beginListenForData()
{
    final Handler handler = new Handler();
    stopThread = false;
    buffer = new byte[1024];
    Thread thread  = new Thread(new Runnable()
    {
        public void run()
        {
            while(!Thread.currentThread().isInterrupted() && !stopThread)
            {
                try
                {
                    int byteCount = inputStream.available();
                    if(byteCount > 0)
                    {
                        byte[] rawBytes = new byte[byteCount];
                        inputStream.read(rawBytes);
                        final String string=new String(rawBytes,"UTF-8");
                        handler.post(new Runnable() {
                            public void run()
                            {
                                textView.append(string);
                            }
                        });

                    }
                }
                catch (IOException ex)
                {
                    stopThread = true;
                    Toast.makeText(getApplicationContext(),"throw4",Toast.LENGTH_SHORT).show();
                }
            }
        }
    });

    thread.start();
}

public void onClickSend(View view) {
    String string = editText.getText().toString();
    string.concat("\n");
    try {
        outputStream.write(string.getBytes());
    } catch (IOException e) {
        e.printStackTrace();
    }
    textView.append("\nSent Data:"+string+"\n");

}

public void onClickStop(View view) throws IOException {
    stopThread = true;
    outputStream.close();
    inputStream.close();
    socket.close();
    setUiEnabled(false);
    deviceConnected=false;
    textView.append("\nConnection Closed!\n");
}

public void onClickClear(View view) {
    textView.setText("");
}

}

我是从All About Circuits的 Hariharan Mathavan this精彩教程中得到的。