Java Android应用程序通信串行数据

Java Android应用程序通信串行数据,java,android,youtube,bluetooth,serial-port,Java,Android,Youtube,Bluetooth,Serial Port,我正在制作一个蓝牙应用程序,它连接到正在传输串行数据的蓝牙发射器/接收器。蓝牙设备最终将连接到传感器,这些传感器将提供需要在手机上显示的数据。到目前为止,我使用模拟软件CoolTerm在我的应用程序和外部蓝牙设备之间来回发送数据。目前,我已成功使应用程序检测并连接到设备。但我遇到了一些问题: 首先,是否有人知道如何安装CoolTerm(从技术上讲,它可以在Mac和windows上使用),但当我尝试在Ubuntu上安装它时,它并没有像在windows上那样提供可执行文件。任何人谁知道如何安装在ub

我正在制作一个蓝牙应用程序,它连接到正在传输串行数据的蓝牙发射器/接收器。蓝牙设备最终将连接到传感器,这些传感器将提供需要在手机上显示的数据。到目前为止,我使用模拟软件CoolTerm在我的应用程序和外部蓝牙设备之间来回发送数据。目前,我已成功使应用程序检测并连接到设备。但我遇到了一些问题:

  • 首先,是否有人知道如何安装CoolTerm(从技术上讲,它可以在Mac和windows上使用),但当我尝试在Ubuntu上安装它时,它并没有像在windows上那样提供可执行文件。任何人谁知道如何安装在ubuntu上,请提供我的步骤,我已经下载了Linux版本的焦油球从那里的网站和解压缩

  • 虽然成功连接后,我的应用程序会发送一个由蓝牙设备接收的字符串,但我无法接收回数据。按照我目前的设置方式,当外部蓝牙设备向我传输数据时,我希望弹出一条toast消息,告诉我已收到数据。CoolTerm软件允许您发送数据,但由于某些原因,我的应用程序上没有显示这些数据。有什么想法吗

  • 最后,任何人都知道一个好的文本框小部件,或者我可以在我的应用程序中使用它将数据发送到外部蓝牙设备。现在,我让应用程序在连接后立即发送一个字符串

  • 这里有一个YouTube链接:我已经按照代码的建议对此做了一些小改动

    点击[此处](“应用程序的youtube视频”)! 点击[此处](“清洁代码formmatt”)

    这是密码

    package com.example.intellicyclemobileside;
    
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.util.ArrayList;
    import java.util.HashSet;
    import java.util.Set;
    import java.util.UUID;
    import android.os.Bundle;
    import android.os.Handler;
    import android.os.Message;
    import android.annotation.SuppressLint;
    import android.app.Activity;
    import android.bluetooth.BluetoothAdapter;
    import android.bluetooth.BluetoothDevice;
    import android.bluetooth.BluetoothSocket;
    import android.content.BroadcastReceiver;
    import android.content.Context;
    import android.content.Intent;
    import android.content.IntentFilter;
    import android.view.Menu;
    import android.view.View;
    import android.widget.AdapterView;
    import android.widget.AdapterView.OnItemClickListener;
    import android.widget.ArrayAdapter;
    import android.widget.Button;
    import android.widget.CompoundButton;
    import android.widget.ListView;
    import android.widget.Toast;
    import android.widget.ToggleButton;
    
    
    public class MainActivity extends Activity {
        ToggleButton toggle_discovery;
        Button button;
        ListView listView;
        BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        ArrayAdapter<String> mArrayAdapter;
        ArrayAdapter<String> adapter;
        ArrayList<String> pairedDevicesList;
        ArrayList<String> unpairedDevicesList;
        ArrayList<String> combinedDevicesList;
        Set<BluetoothDevice> pairedDevices;
        Set<String> unpairedDevices;
        BroadcastReceiver mReceiver;
        String selectedFromList;
        String selectedFromListName;
        String selectedFromListAddress;
        BluetoothDevice selectedDevice;
    
    /*
        public BluetoothSocket mmSocket;
        public BluetoothDevice mmDevice;*/
        protected static final int SUCCESS_CONNECT = 0;
        protected static final int MESSAGE_READ = 1;
        final int STATE_CONNECTED = 2;
        final int STATE_CONNECTING = 1;
        final int STATE_DISCONNECTED = 0;
        private final UUID MY_UUID = UUID.fromString("0001101-0000-1000-8000-00805F9B34FB");
        private static final int REQUEST_ENABLE_BT = 1;
    
    
        Handler mHandler = new Handler(){           
        public void handleMessage(Message msg){
            super.handleMessage(msg);
            switch(msg.what){
                case SUCCESS_CONNECT:
                    // Do Something;
                    ConnectedThread connectedThread = new ConnectedThread((BluetoothSocket)msg.obj);
                    Toast.makeText(getApplicationContext(),"CONNECTED",0).show();
                    String s = "This string proves a socket connection has been established!!";
                    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.activity_main);
        button = (Button) findViewById(R.id.findDevices);
        toggle_discovery =  (ToggleButton) findViewById(R.id.deviceDiscoverable);
        pairedDevicesList = new ArrayList<String>();
        unpairedDevicesList = new ArrayList<String>();
        unpairedDevices = new HashSet<String>();
        listView = (ListView)findViewById(R.id.listView); 
    
        // Sets up Bluetooth
        enableBT();
    
        button.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                // Perform action on click
                Toast.makeText(getApplicationContext(), "Searching for devices, please wait... ",Toast.LENGTH_SHORT).show();
                // Checks for known paired devices
                pairedDevices = mBluetoothAdapter.getBondedDevices();   
                displayCominedDevices();
                //mBluetoothAdapter.cancelDiscovery();
               }
             });
    
    toggle_discovery.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (isChecked) {
        makeDicoverable(1);
        } else {
           // The toggle is disabled
           makeDicoverable(0);
          }
        }
    });
    
    listView.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
        // When clicked, show a toast with the TextView text
        selectedFromList = (String) (listView.getItemAtPosition(position));
        /*Debugging
        Toast.makeText(getApplicationContext(), selectedFromList,Toast.LENGTH_SHORT).show();*/
            String[] parts = selectedFromList.split(" ");
        selectedFromListName = parts[0];
        selectedFromListAddress = parts[1];
        BluetoothDevice selectedDevice = selectedDevice(selectedFromListAddress);
        mBluetoothAdapter.cancelDiscovery();
        ConnectThread ct = new ConnectThread(selectedDevice);
        ct.start();
        //ConnectThread ConnectThread = new ConnectThread(selectedDevice);
        //connectDevice();
        /* Debug Help
        Toast.makeText(getApplicationContext(), selectedFromListName,Toast.LENGTH_SHORT).show();
        Toast.makeText(getApplicationContext(), selectedFromListAddress,Toast.LENGTH_SHORT).show();
                                         Toast.makeText(getApplicationContext(),selectedDevice.getAddress(), Toast.LENGTH_SHORT).show();*/
             }
      });
    }
    
    
    public void displayCominedDevices(){
        displayPairedDevices();
        displayDetectedDevices();
        mArrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,removeDuplicates(unpairedDevicesList,pairedDevicesList));
        listView.setAdapter(mArrayAdapter);
    }
    
    public BluetoothDevice selectedDevice(String deviceAddress){
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        BluetoothDevice device;     
        device = mBluetoothAdapter.getRemoteDevice(deviceAddress);
        return device;
    }
    
    @SuppressLint("NewApi")
    public String checkState(BluetoothSocket mmSocket2){
        String state = "NOT_KNOWN";
    
        if (mmSocket2.isConnected() == true){
            state = "STATE_CONNECTED";
        }
            state = "STATE_DISCONNECTED";
    
        Toast.makeText(getApplicationContext(), state, Toast.LENGTH_SHORT).show();
    
        return state;
    }
    
    
    @SuppressWarnings("unchecked")
    public ArrayList<String> removeDuplicates(ArrayList<String> s1, ArrayList<String> s2){
        /*Debugging 
        Toast.makeText(getApplication(), "unpairedList " + s1.toString(),Toast.LENGTH_LONG).show();
        Toast.makeText(getApplication(), "pairedList " + s2.toString(),Toast.LENGTH_LONG).show(); */
        combinedDevicesList =  new ArrayList<String>();
        combinedDevicesList.addAll(s1);
        combinedDevicesList.addAll(s2);
        @SuppressWarnings("unchecked")
        Set Unique_set = new HashSet(combinedDevicesList);
        combinedDevicesList = new ArrayList<String>(Unique_set);
        /*Debugging 
        Toast.makeText(getApplication(),"Combined List" + combinedDevicesList.toString(),Toast.LENGTH_LONG).show(); */
        return combinedDevicesList;
    }
    
    public void enableBT(){
        if (mBluetoothAdapter == null) {
            // Device does not support Bluetooth
            Toast.makeText(getApplicationContext(), "Bluetooth is not suppourted on Device",Toast.LENGTH_SHORT).show();
        }
    
        if (!mBluetoothAdapter.isEnabled()) {
           Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
           startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
           int resultCode = Activity.RESULT_OK;
            if(resultCode < 1){
                Toast.makeText(getApplicationContext(), "Please Accept Enabling Bluetooth Request!", Toast.LENGTH_LONG).show();
            }
            else{
                Toast.makeText(getApplicationContext(), "Enabling Bluetooth FAILED!", Toast.LENGTH_SHORT).show();
            }
        }
    }
    
    public void displayPairedDevices(){
        // If there are paired devices
        enableBT();
        if (pairedDevices.size() > 0) {
            //Toast.makeText(getApplicationContext(),"in loop",Toast.LENGTH_SHORT).show();
            // Loop through paired devices
            for (BluetoothDevice device : pairedDevices) {
                // Add the name and address to an array adapter to show in a ListView
                String s = " ";
                String deviceName = device.getName();
                String deviceAddress = device.getAddress();
                pairedDevicesList.add(deviceName + s + deviceAddress +" \n");
                //listView.setAdapter(mArrayAdapter);
                //Toast.makeText(getApplicationContext(), device.getName(),Toast.LENGTH_SHORT).show();
           }
    
    
            /*
            mArrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,pairedDevicesList);
            listView.setAdapter(mArrayAdapter);*/
        }
    }
    
    public void displayDetectedDevices(){
        mBluetoothAdapter.startDiscovery();
    
        // Create a BroadcastReceiver for ACTION_FOUND
        mReceiver = new BroadcastReceiver() {
            @SuppressWarnings("static-access")
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
                /* Debugging help
                Toast.makeText(getApplicationContext(),action,Toast.LENGTH_SHORT).show();*/
                // When discovery finds a device
                if(BluetoothDevice.ACTION_FOUND.equals(action)){
                    BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                    /* Debugging help
                    Toast.makeText(getApplicationContext(),device.getName(),Toast.LENGTH_SHORT).show();*/
                    String deviceName = device.getName();
                    String deviceAddress = device.getAddress();
                    String s = " ";
                    unpairedDevices.add(deviceName + s + deviceAddress +" \n");
                    //unpairedDevicesList.add(deviceName + s + deviceAddress +" (un-paired)\n");
                    unpairedDevicesList = new ArrayList<String>(unpairedDevices);
                }
            }
        };
        /*adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,unpairedDevicesList);
        listView.setAdapter(adapter);*/
        // Register the BroadcastReceiver      
        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        registerReceiver(mReceiver, filter); // Don't forget to unregister during onDestroy
        //Toast.makeText(getApplicationContext(), unpairedDevicesList.toString(), Toast.LENGTH_LONG).show();
    
    }
    
    public void makeDicoverable(int option){
        Intent discoverableIntent;
        if (option == 1){
            discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
            discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,120);
            startActivity(discoverableIntent);
    
    
            Toast.makeText(getApplicationContext(), "Open discovery for 2mins", Toast.LENGTH_SHORT).show();
        } else {
            discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
            discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 1);
            startActivity(discoverableIntent);
            Toast.makeText(getApplicationContext(), "Open discovery is OFF!", Toast.LENGTH_SHORT).show();
        }
    }
    /*Un-used Method
    public void compareAddress(BluetoothDevice checkDevice,String address){
        if((checkDevice.getAddress().equals(address))){
    
            selectedDevice = checkDevice;
        }   
    
    }*/
    
    @SuppressLint("NewApi")
    public 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
            mBluetoothAdapter.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) {
                    Toast.makeText(getApplicationContext(), "Connecting to device failed!", Toast.LENGTH_LONG).show();
                }
                    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 {
                    // Read from the InputStream
                    buffer = new byte[1024];
                    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) { }
        }
    }
    
    }
    
    package com.example.intellicyclemobileside;
    导入java.io.IOException;
    导入java.io.InputStream;
    导入java.io.OutputStream;
    导入java.util.ArrayList;
    导入java.util.HashSet;
    导入java.util.Set;
    导入java.util.UUID;
    导入android.os.Bundle;
    导入android.os.Handler;
    导入android.os.Message;
    导入android.annotation.SuppressLint;
    导入android.app.Activity;
    导入android.bluetooth.BluetoothAdapter;
    导入android.bluetooth.bluetooth设备;
    导入android.bluetooth.BluetoothSocket;
    导入android.content.BroadcastReceiver;
    导入android.content.Context;
    导入android.content.Intent;
    导入android.content.IntentFilter;
    导入android.view.Menu;
    导入android.view.view;
    导入android.widget.AdapterView;
    导入android.widget.AdapterView.OnItemClickListener;
    导入android.widget.ArrayAdapter;
    导入android.widget.Button;
    导入android.widget.CompoundButton;
    导入android.widget.ListView;
    导入android.widget.Toast;
    导入android.widget.ToggleButton;
    公共类MainActivity扩展了活动{
    切换按钮切换搜索;
    按钮;
    列表视图列表视图;
    BluetoothAdapter mBluetoothAdapter=BluetoothAdapter.getDefaultAdapter();
    ArrayAdapter mArrayAdapter;
    阵列适配器;
    ArrayList PairedDeviceList;
    ArrayList未配对设备列表;
    ArrayList组合设备列表;
    设置配对设备;
    设置不成对的设备;
    广播接收机;
    从列表中选择的字符串;
    从ListName中选择的字符串;
    从ListAddress中选择的字符串;
    蓝牙设备选择设备;
    /*
    公共蓝牙插座;
    公共蓝牙设备*/
    受保护的静态最终int成功连接=0;
    受保护的静态最终int消息_READ=1;
    最终int状态_连接=2;
    最终int状态_连接=1;
    最终int状态_断开=0;
    私有最终UUID MY_UUID=UUID.fromString(“0001101-0000-1000-8000-00805F9B34FB”);
    私有静态最终整数请求_ENABLE_BT=1;
    Handler mHandler=新的Handler(){
    公共无效handleMessage(消息消息消息){
    超级handleMessage(msg);
    开关(msg.what){
    成功案例(u CONNECT):
    //做点什么;
    ConnectedThread ConnectedThread=新的ConnectedThread((BluetoothSocket)msg.obj);
    Toast.makeText(getApplicationContext(),“CONNECTED”,0.show();
    String s=“此字符串证明已建立套接字连接!!”;
    connectedThread.write(s.getBytes());
    打破
    案例信息如下:
    字节[]readBuf=(字节[])msg.obj;
    字符串字符串=新字符串(readBuf);
    Toast.makeText(getApplicationContext(),string,0.show();
    打破
    }       
    }
    };
    @凌驾
    创建时受保护的void(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    按钮=(按钮)findViewById(R.id.findDevices);
    toggle_discovery=(ToggleButton)findviewbyd(R.id.deviceDiscoverable);
    PairedDeviceList=新的ArrayList();
    unpairedDeviceList=新的ArrayList();
    unpairedDevices=新HashSet();
    listView=(listView)findViewById(R.id.listView);
    //设置蓝牙
    enableBT();
    setOnClickListener(新视图.OnClickListener(){
    公共void onClick(视图v){
    //单击后执行操作
    Toast.makeText(getApplicationContext(),“正在搜索设备,请稍候…”,Toast.LENGTH\u SHORT.show();
    //检查已知的配对设备
    pairedDevices=mBluetoothAdapter.getBondedDevices();
    displayCominedDevices();
    //mBluetoothAdapter.cancelDiscovery();
    }
    });
    切换_discovery.setOnCheckedChangeListener(新建CompoundButton.OnCheckedChangeListener()){
    检查更改后的公共无效(复合按钮视图,布尔值已检查){
    如果(已检查){
    可更换(1);
    }否则{
    //切换被禁用
    makeDicoverable(0);
    }
    }
    });
    setOnItemClickListener(新的OnItemClickListener(){
    public void onItemClick(适配器视图父级、视图视图、整数位置)