用于蓝牙通信的Android应用程序

时间:2014-08-26 08:18:03

标签: android bluetooth android-bluetooth

我为我们的项目编写了一个应用程序。

我写过在youtube上观看教程。

通过蓝牙进行通信。

设备已配对并与设备连接,设备会将成功连接字符串发送回终端。

但是我发送的数据没有被设备接收。(有一个用于显示接收数据的Toast消息)。

请澄清,这是我的代码

public class MainActivity extends Activity implements OnItemClickListener {

protected static final int SUCCESS_CONNECT = 0;
protected static final int MESSAGE_READ = 1;
ArrayAdapter<String> listAdapter;
ListView listView;
BluetoothAdapter btAdapter;
Set<BluetoothDevice> devicesArray;
ArrayList<String> pairedDevices;
IntentFilter filter;
BroadcastReceiver receiver;
String tag = "debugging";
ArrayList<BluetoothDevice> devices;
public static UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");

Handler mHandler = new Handler(){
    public void handleMessage(android.os.Message msg) {
        switch(msg.what){
        case SUCCESS_CONNECT:
            ConnectedThread connectedThread = new ConnectedThread((BluetoothSocket)msg.obj);
            Toast.makeText(getApplicationContext(), "Successfully Connected", 0).show();
            String s = "Successfully Connected";
            connectedThread.write(s.getBytes());
            break;
        case MESSAGE_READ:
            byte[] readbuf = (byte[])msg.obj;
            String string = new String(readbuf);
            Toast.makeText(getApplicationContext(), string, 0).show();
            break;
        }
    }
};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    init();
    if(btAdapter == null){
        Toast.makeText(getApplicationContext(), "No Bluetooth Detected", 0).show();
        finish();
    }
    else{
        if(!btAdapter.isEnabled()){
            turnOnBT();
        }
        getPairedDevices();
        startDiscovery();
    }
}

private void startDiscovery() {
    // TODO Auto-generated method stub
    btAdapter.cancelDiscovery();
    btAdapter.startDiscovery();
}

private void turnOnBT() {
    // TODO Auto-generated method stub
    Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
    startActivityForResult(intent, 1);
}

private void getPairedDevices() {
    // TODO Auto-generated method stub
    devicesArray = btAdapter.getBondedDevices();
    if(devicesArray.size()>0){
        for(BluetoothDevice device: devicesArray){
            pairedDevices.add(device.getName());
        }
    }
}


//initializes all the variables
private void init() {
    // TODO Auto-generated method stub
    listView = (ListView)findViewById(R.id.listView);
    listView.setOnItemClickListener(this);
    listAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,0);
    listView.setAdapter(listAdapter);
    btAdapter = BluetoothAdapter.getDefaultAdapter();
    pairedDevices = new ArrayList<String>();
    devices = new ArrayList<BluetoothDevice>();
    filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
    receiver = new BroadcastReceiver(){
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            // When discovery finds a device
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                // Get the BluetoothDevice object from the Intent
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                devices.add(device);
                String s = "";
                for(int i = 0 ; i< pairedDevices.size(); i++){
                    if(device.getName().equals(pairedDevices.get(i))){
                        s ="(PAIRED)";
                        break;                          
                    }
                }
                listAdapter.add(device.getName()+" "+s+"\n"+device.getAddress());
            }
            else if(BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)){
                //some code
            }
            else if(BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)){
                //some code
            }
            else if(BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)){
                if(btAdapter.getState() == btAdapter.STATE_OFF){
                    turnOnBT();
                }
            }
        }
    };
    registerReceiver(receiver, filter);
    filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
    registerReceiver(receiver, filter);
    filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
    registerReceiver(receiver, filter);
    filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
    registerReceiver(receiver, filter);
}
@Override
protected void onPause() {
    // TODO Auto-generated method stub
    super.onPause();
    unregisterReceiver(receiver);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // TODO Auto-generated method stub
    super.onActivityResult(requestCode, resultCode, data);
    if(resultCode == RESULT_CANCELED){
        Toast.makeText(getApplicationContext(), "Bluetooth must be enabled", Toast.LENGTH_SHORT).show();
        finish();
    }
}

@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
//public abstract void onItemClick (AdapterView<?> parent, View view, int position, long id)
    // TODO Auto-generated method stub
    if(btAdapter.isDiscovering()){
        btAdapter.cancelDiscovery();
    }
    if(listAdapter.getItem(arg2).contains("(PAIRED)")){
        //Toast.makeText(getApplicationContext(), "Device is Already Paired", 0).show();
        BluetoothDevice selectedDevice = devices.get(arg2);
        ConnectThread connect = new ConnectThread(selectedDevice);
        connect.start();
        Log.i(tag,"in click listener");
    }
    else{
        Toast.makeText(getApplicationContext(), "Device is not Paired", 0).show();
    }
}

private class ConnectThread extends Thread {

    private final BluetoothSocket mmSocket;
    private final BluetoothDevice mmDevice;

    public ConnectThread(BluetoothDevice device) {
        // Use a temporary object that is later assigned to mmSocket,
        // because mmSocket is final
        BluetoothSocket tmp = null;
        mmDevice = device;

        // Get a BluetoothSocket to connect with the given BluetoothDevice
        try {
            // MY_UUID is the app's UUID string, also used by the server code
            tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
        } catch (IOException e) { }
        mmSocket = tmp;
    }

    public void run() {
        // Cancel discovery because it will slow down the connection
        btAdapter.cancelDiscovery();

        try {
            // Connect the device through the socket. This will block
            // until it succeeds or throws an exception
            mmSocket.connect();
        } catch (IOException connectException) {
            // Unable to connect; close the socket and get out
            try {
                mmSocket.close();
            } catch (IOException closeException) { }
            return;
        }

        // Do work to manage the connection (in a separate thread)

        mHandler.obtainMessage(SUCCESS_CONNECT,mmSocket).sendToTarget();
    }

    /** Will cancel an in-progress connection, and close the socket */
    public void cancel() {
        try {
            mmSocket.close();
        } catch (IOException e) { }
    }
}
private class ConnectedThread extends Thread {
    private final BluetoothSocket mmSocket;
    private final InputStream mmInStream;
    private final OutputStream mmOutStream;

    public ConnectedThread(BluetoothSocket socket) {
        mmSocket = socket;
        InputStream tmpIn = null;
        OutputStream tmpOut = null;

        // Get the input and output streams, using temp objects because
        // member streams are final
        try {
            tmpIn = socket.getInputStream();
            tmpOut = socket.getOutputStream();
        } catch (IOException e) { }

        mmInStream = tmpIn;
        mmOutStream = tmpOut;
    }

    public void run() {
        byte[] buffer;  // buffer store for the stream
        int bytes; // bytes returned from read()

        // Keep listening to the InputStream until an exception occurs
        while (true) {
            try {
                buffer = new byte[1024];
                // Read from the InputStream
                bytes = mmInStream.read(buffer);
                // Send the obtained bytes to the UI activity
                mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer).sendToTarget();
            } catch (IOException e) {
                break;
            }
        }
    }

    /* Call this from the main activity to send data to the remote device */
    public void write(byte[] bytes) {
        try {
            mmOutStream.write(bytes);
        } catch (IOException e) { }
       }

    /* Call this from the main activity to shutdown the connection */
    public void cancel() {
        try {
            mmSocket.close();
        } catch (IOException e) { }
     }
   }
}

1 个答案:

答案 0 :(得分:0)

连接蓝牙模块时,从BluetoothDevice对象获取地址。使用以下示例代码连接蓝牙设备。它适合我。

for(BluetoothDevice bt: mBluetoothAdapter.getBondedDevices()) {
    if(bt.getName().equalsIgnoreCase(selectedBTDeviceName)) {
        BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(bt.getAddress());
        mBluetoothAdapter.cancelDiscovery();

        mBSocket = device.createRfcommSocketToServiceRecord(SPP_UUID);
        mBSocket.connect();
        return mBSocket;
    }
}

您确实使用device.getAddress()方法创建了BluetoothDevice对象。现在唯一可能出现的问题是你的BroadcastReceiver。

在您从 onCreate()调用的 init()方法中,您正在注册 BroadcastReceiver 使用此活动并在 onPause()中取消注册BroadcastReceiver。

  

onResume()方法中注册,以便您可以接收   在您恢复此活动时广播。