java - Android应用程序通信串口数据

标签 java android youtube bluetooth serial-port

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

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

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

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

这是一个 YouTube 链接:我按照代码的建议对此做了一些细微的更改。

点击[此处](http://www.youtube.com/watch?v=r55C77_ohi8“应用程序的youtube视频”)! 单击[此处](https://drive.google.com/?tab=mo&authuser=0#folders/0BwRY4KO_k7sUSGpLX0o4TDFCOFk“更清晰的代码格式”)!

这是代码

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) { }
    }
}

}

最佳答案

如果您的设备是“蓝牙到 UART 转换器”模块,则在模块处进行环回连接(即短接 TXD 和 RXD)。将测试字符串从您的应用程序发送到模块,并期望也收到它。根据此类测试的结果,可以进一步探测您的应用程序或/和模块以恢复真正的问题(如果有)。

关于java - Android应用程序通信串口数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21617928/

相关文章:

java - 如何在 WebSphere Liberty Batch 中配置事务超时?

java - 使用 java.time 生成一个随机的 LocalDate

android - 如果已经有 drawable - hpi, mdpi, xhdpi,xxhdpi, xxxhdpi,我们还需要 Android Resources 中的 drawable 文件夹吗

android - python请求模块错误,kivy Android app中 'temporary failure in name resolution'

javascript - 使用 javascript,当用户单击播放时,如何使 YouTube 视频进入全屏?

javascript - 嵌入式 YouTube 视频在封闭容器中继续播放

python - 使用 Python 终止 Linux 进程 - ffmpeg 终止到 Youtube 的实时流

java - Spring中bean的初始化顺序

java - Android/Java 中的网络 - 如何在从服务器回调后回调到 API 类?

android - 为 FrameLayout 内的所有自定义 View 触发 OnClickListener