使用BluetoothChat与ELM327通信

2023-11-28

我目前正在尝试通过 BluetoothChat 示例应用程序与 ELM327 OBDII 蓝牙适配器进行通信。我可以连接,因为我更改了 UUID,但是我只能接收启动命令和提示“>”来发送命令,每当我尝试发送命令时,我都会收到以下信息

  • CAN OBDII:ELM327 v1.2a>
  • Me:ATRV
  • CAN OBDII:ATRV
  • CAN OBDII:>
  • OBDII 可以吗:?

现在我在这里阅读以将“\r”附加到命令中,但是当我这样做时,我得到了完全相同的响应。我正在使用示例应用程序“BluetoothChat”

主班...

public class BluetoothChat extends Activity {
    // Debugging
    private static final String TAG = "BluetoothChat";
    private static final boolean D = true;

    // Message types sent from the BluetoothChatService Handler
    public static final int MESSAGE_STATE_CHANGE = 1;
    public static final int MESSAGE_READ = 2;
    public static final int MESSAGE_WRITE = 3;
    public static final int MESSAGE_DEVICE_NAME = 4;
    public static final int MESSAGE_TOAST = 5;

    // Key names received from the BluetoothChatService Handler
    public static final String DEVICE_NAME = "device_name";
    public static final String TOAST = "toast";

    // Intent request codes
    private static final int REQUEST_CONNECT_DEVICE_SECURE = 1;
    private static final int REQUEST_CONNECT_DEVICE_INSECURE = 2;
    private static final int REQUEST_ENABLE_BT = 3;

    // Layout Views
    private TextView mTitle;
    private ListView mConversationView;
    private EditText mOutEditText;
    private Button mSendButton;

    // Name of the connected device
    private String mConnectedDeviceName = null;
    // Array adapter for the conversation thread
    private ArrayAdapter<String> mConversationArrayAdapter;
    // String buffer for outgoing messages
    private StringBuffer mOutStringBuffer;
    // Local Bluetooth adapter
    private BluetoothAdapter mBluetoothAdapter = null;
    // Member object for the chat services
    private BluetoothChatService mChatService = null;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if(D) Log.e(TAG, "+++ ON CREATE +++");

        // Set up the window layout
        requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
        setContentView(R.layout.main);
        getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title);

        // Set up the custom title
        mTitle = (TextView) findViewById(R.id.title_left_text);
        mTitle.setText(R.string.app_name);
        mTitle = (TextView) findViewById(R.id.title_right_text);

        // Get local Bluetooth adapter
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

        // If the adapter is null, then Bluetooth is not supported
        if (mBluetoothAdapter == null) {
            Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
            finish();
            return;
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        if(D) Log.e(TAG, "++ ON START ++");

        // If BT is not on, request that it be enabled.
        // setupChat() will then be called during onActivityResult
        if (!mBluetoothAdapter.isEnabled()) {
            Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
        // Otherwise, setup the chat session
        } else {
            if (mChatService == null) setupChat();
        }
    }

    @Override
    public synchronized void onResume() {
        super.onResume();
        if(D) Log.e(TAG, "+ ON RESUME +");

        // Performing this check in onResume() covers the case in which BT was
        // not enabled during onStart(), so we were paused to enable it...
        // onResume() will be called when ACTION_REQUEST_ENABLE activity returns.
        if (mChatService != null) {
            // Only if the state is STATE_NONE, do we know that we haven't started already
            if (mChatService.getState() == BluetoothChatService.STATE_NONE) {
              // Start the Bluetooth chat services
              mChatService.start();
            }
        }
    }

    private void setupChat() {
        Log.d(TAG, "setupChat()");

        // Initialize the array adapter for the conversation thread
        mConversationArrayAdapter = new ArrayAdapter<String>(this, R.layout.message);
        mConversationView = (ListView) findViewById(R.id.in);
        mConversationView.setAdapter(mConversationArrayAdapter);

        // Initialize the compose field with a listener for the return key
        mOutEditText = (EditText) findViewById(R.id.edit_text_out);
        mOutEditText.setOnEditorActionListener(mWriteListener);

        // Initialize the send button with a listener that for click events
        mSendButton = (Button) findViewById(R.id.button_send);
        mSendButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                // Send a message using content of the edit text widget
                TextView view = (TextView) findViewById(R.id.edit_text_out);
                String message = view.getText().toString();
                sendMessage(message);
            }
        });

        // Initialize the BluetoothChatService to perform bluetooth connections
        mChatService = new BluetoothChatService(this, mHandler);

        // Initialize the buffer for outgoing messages
        mOutStringBuffer = new StringBuffer("");
    }

    @Override
    public synchronized void onPause() {
        super.onPause();
        if(D) Log.e(TAG, "- ON PAUSE -");
    }

    @Override
    public void onStop() {
        super.onStop();
        if(D) Log.e(TAG, "-- ON STOP --");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        // Stop the Bluetooth chat services
        if (mChatService != null) mChatService.stop();
        if(D) Log.e(TAG, "--- ON DESTROY ---");
    }

    private void ensureDiscoverable() {
        if(D) Log.d(TAG, "ensure discoverable");
        if (mBluetoothAdapter.getScanMode() !=
            BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
            Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
            discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
            startActivity(discoverableIntent);
        }
    }

    /**
     * Sends a message.
     * @param message  A string of text to send.
     */
    private void sendMessage(String message) {
        // Check that we're actually connected before trying anything
        if (mChatService.getState() != BluetoothChatService.STATE_CONNECTED) {
            Toast.makeText(this, R.string.not_connected, Toast.LENGTH_SHORT).show();
            return;
        }

        // Check that there's actually something to send
        if (message.length() > 0) {
            // Get the message bytes and tell the BluetoothChatService to write
            byte[] send = message.getBytes();
            mChatService.write(send);

            // Reset out string buffer to zero and clear the edit text field
            mOutStringBuffer.setLength(0);
            mOutEditText.setText(mOutStringBuffer);
        }
    }

    // The action listener for the EditText widget, to listen for the return key
    private TextView.OnEditorActionListener mWriteListener =
        new TextView.OnEditorActionListener() {
        public boolean onEditorAction(TextView view, int actionId, KeyEvent event) {
            // If the action is a key-up event on the return key, send the message
            if (actionId == EditorInfo.IME_NULL && event.getAction() == KeyEvent.ACTION_UP) {
                String message = view.getText().toString();
                sendMessage(message);
            }
            if(D) Log.i(TAG, "END onEditorAction");
            return true;
        }
    };

    // The Handler that gets information back from the BluetoothChatService
    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case MESSAGE_STATE_CHANGE:
                if(D) Log.i(TAG, "MESSAGE_STATE_CHANGE: " + msg.arg1);
                switch (msg.arg1) {
                case BluetoothChatService.STATE_CONNECTED:
                    mTitle.setText(R.string.title_connected_to);
                    mTitle.append(mConnectedDeviceName);
                    mConversationArrayAdapter.clear();
                    break;
                case BluetoothChatService.STATE_CONNECTING:
                    mTitle.setText(R.string.title_connecting);
                    break;
                case BluetoothChatService.STATE_LISTEN:
                case BluetoothChatService.STATE_NONE:
                    mTitle.setText(R.string.title_not_connected);
                    break;
                }
                break;
            case MESSAGE_WRITE:
                Log.i(TAG, "WRITING!");
                byte[] writeBuf = (byte[]) msg.obj;
                // construct a string from the buffer
                String writeMessage = new String(writeBuf);
                mConversationArrayAdapter.add("Me:  " + writeMessage);
                break;
            case MESSAGE_READ:
                Log.i(TAG, "READING");
                String readMessage = (String) msg.obj;

                // construct a string from the valid bytes in the buffer

                mConversationArrayAdapter.add(mConnectedDeviceName+":  " + readMessage);
                break;
            case MESSAGE_DEVICE_NAME:
                // save the connected device's name
                mConnectedDeviceName = msg.getData().getString(DEVICE_NAME);
                Toast.makeText(getApplicationContext(), "Connected to "
                               + mConnectedDeviceName, Toast.LENGTH_SHORT).show();
                break;
            case MESSAGE_TOAST:
                Toast.makeText(getApplicationContext(), msg.getData().getString(TOAST),
                               Toast.LENGTH_SHORT).show();
                break;
            }
        }
    };

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(D) Log.d(TAG, "onActivityResult " + resultCode);
        switch (requestCode) {
        case REQUEST_CONNECT_DEVICE_SECURE:
            // When DeviceListActivity returns with a device to connect
            if (resultCode == Activity.RESULT_OK) {
                connectDevice(data, true);
            }
            break;
        case REQUEST_CONNECT_DEVICE_INSECURE:
            // When DeviceListActivity returns with a device to connect
            if (resultCode == Activity.RESULT_OK) {
                connectDevice(data, false);
            }
            break;
        case REQUEST_ENABLE_BT:
            // When the request to enable Bluetooth returns
            if (resultCode == Activity.RESULT_OK) {
                // Bluetooth is now enabled, so set up a chat session
                setupChat();
            } else {
                // User did not enable Bluetooth or an error occured
                Log.d(TAG, "BT not enabled");
                Toast.makeText(this, R.string.bt_not_enabled_leaving, Toast.LENGTH_SHORT).show();
                finish();
            }
        }
    }

    private void connectDevice(Intent data, boolean secure) {
        // Get the device MAC address
        String address = data.getExtras()
            .getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
        // Get the BLuetoothDevice object
        BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
        // Attempt to connect to the device
        mChatService.connect(device, secure);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.option_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        Intent serverIntent = null;
        switch (item.getItemId()) {
        case R.id.secure_connect_scan:
            // Launch the DeviceListActivity to see devices and do scan
            serverIntent = new Intent(this, DeviceListActivity.class);
            startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE_SECURE);
            return true;
        case R.id.insecure_connect_scan:
            // Launch the DeviceListActivity to see devices and do scan
            serverIntent = new Intent(this, DeviceListActivity.class);
            startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE_INSECURE);
            return true;
        case R.id.discoverable:
            // Ensure this device is discoverable by others
            ensureDiscoverable();
            return true;
        }
        return false;
    }

}










package com.example.android.BluetoothChat;

import java.io.IOException;

/**
 * This class does all the work for setting up and managing Bluetooth
 * connections with other devices. It has a thread that listens for
 * incoming connections, a thread for connecting with a device, and a
 * thread for performing data transmissions when connected.
 */
public class BluetoothChatService {
    // Debugging
    private static final String TAG = "BluetoothChatService";
    private static final boolean D = true;

    // Name for the SDP record when creating server socket
    private static final String NAME_SECURE = "BluetoothChatSecure";
    private static final String NAME_INSECURE = "BluetoothChatInsecure";

    // Unique UUID for this application
    private static final UUID MY_UUID_SECURE =
        UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
    private static final UUID MY_UUID_INSECURE =
        UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");

    // Member fields
    private final BluetoothAdapter mAdapter;
    private final Handler mHandler;
    private AcceptThread mSecureAcceptThread;
    private AcceptThread mInsecureAcceptThread;
    private ConnectThread mConnectThread;
    private ConnectedThread mConnectedThread;
    private int mState;

    // Constants that indicate the current connection state
    public static final int STATE_NONE = 0;       // we're doing nothing
    public static final int STATE_LISTEN = 1;     // now listening for incoming connections
    public static final int STATE_CONNECTING = 2; // now initiating an outgoing connection
    public static final int STATE_CONNECTED = 3;  // now connected to a remote device

    /**
     * Constructor. Prepares a new BluetoothChat session.
     * @param context  The UI Activity Context
     * @param handler  A Handler to send messages back to the UI Activity
     */
    public BluetoothChatService(Context context, Handler handler) {
        mAdapter = BluetoothAdapter.getDefaultAdapter();
        mState = STATE_NONE;
        mHandler = handler;
    }

    /**
     * Set the current state of the chat connection
     * @param state  An integer defining the current connection state
     */
    private synchronized void setState(int state) {
        if (D) Log.d(TAG, "setState() " + mState + " -> " + state);
        mState = state;

        // Give the new state to the Handler so the UI Activity can update
        mHandler.obtainMessage(BluetoothChat.MESSAGE_STATE_CHANGE, state, -1).sendToTarget();
    }

    /**
     * Return the current connection state. */
    public synchronized int getState() {
        return mState;
    }

    /**
     * Start the chat service. Specifically start AcceptThread to begin a
     * session in listening (server) mode. Called by the Activity onResume() */
    public synchronized void start() {
        if (D) Log.d(TAG, "start");

        // Cancel any thread attempting to make a connection
        if (mConnectThread != null) {mConnectThread.cancel(); mConnectThread = null;}

        // Cancel any thread currently running a connection
        if (mConnectedThread != null) {mConnectedThread.cancel(); mConnectedThread = null;}

        setState(STATE_LISTEN);

        // Start the thread to listen on a BluetoothServerSocket
        if (mSecureAcceptThread == null) {
            mSecureAcceptThread = new AcceptThread(true);
            mSecureAcceptThread.start();
        }
        if (mInsecureAcceptThread == null) {
            mInsecureAcceptThread = new AcceptThread(false);
            mInsecureAcceptThread.start();
        }
    }

    /**
     * Start the ConnectThread to initiate a connection to a remote device.
     * @param device  The BluetoothDevice to connect
     * @param secure Socket Security type - Secure (true) , Insecure (false)
     */
    public synchronized void connect(BluetoothDevice device, boolean secure) {
        if (D) Log.d(TAG, "connect to: " + device);

        // Cancel any thread attempting to make a connection
        if (mState == STATE_CONNECTING) {
            if (mConnectThread != null) {mConnectThread.cancel(); mConnectThread = null;}
        }

        // Cancel any thread currently running a connection
        if (mConnectedThread != null) {mConnectedThread.cancel(); mConnectedThread = null;}

        // Start the thread to connect with the given device
        mConnectThread = new ConnectThread(device, secure);
        mConnectThread.start();
        setState(STATE_CONNECTING);
    }

    /**
     * Start the ConnectedThread to begin managing a Bluetooth connection
     * @param socket  The BluetoothSocket on which the connection was made
     * @param device  The BluetoothDevice that has been connected
     */
    public synchronized void connected(BluetoothSocket socket, BluetoothDevice
            device, final String socketType) {
        if (D) Log.d(TAG, "connected, Socket Type:" + socketType);

        // Cancel the thread that completed the connection
        if (mConnectThread != null) {mConnectThread.cancel(); mConnectThread = null;}

        // Cancel any thread currently running a connection
        if (mConnectedThread != null) {mConnectedThread.cancel(); mConnectedThread = null;}

        // Cancel the accept thread because we only want to connect to one device
        if (mSecureAcceptThread != null) {
            mSecureAcceptThread.cancel();
            mSecureAcceptThread = null;
        }
        if (mInsecureAcceptThread != null) {
            mInsecureAcceptThread.cancel();
            mInsecureAcceptThread = null;
        }

        // Start the thread to manage the connection and perform transmissions
        mConnectedThread = new ConnectedThread(socket, socketType);
        mConnectedThread.start();

        // Send the name of the connected device back to the UI Activity
        Message msg = mHandler.obtainMessage(BluetoothChat.MESSAGE_DEVICE_NAME);
        Bundle bundle = new Bundle();
        bundle.putString(BluetoothChat.DEVICE_NAME, device.getName());
        msg.setData(bundle);
        mHandler.sendMessage(msg);

        setState(STATE_CONNECTED);
    }

    /**
     * Stop all threads
     */
    public synchronized void stop() {
        if (D) Log.d(TAG, "stop");

        if (mConnectThread != null) {
            mConnectThread.cancel();
            mConnectThread = null;
        }

        if (mConnectedThread != null) {
            mConnectedThread.cancel();
            mConnectedThread = null;
        }

        if (mSecureAcceptThread != null) {
            mSecureAcceptThread.cancel();
            mSecureAcceptThread = null;
        }

        if (mInsecureAcceptThread != null) {
            mInsecureAcceptThread.cancel();
            mInsecureAcceptThread = null;
        }
        setState(STATE_NONE);
    }

    /**
     * Write to the ConnectedThread in an unsynchronized manner
     * @param out The bytes to write
     * @see ConnectedThread#write(byte[])
     */
    public void write(byte[] out) {
        // Create temporary object
        ConnectedThread r;
        // Synchronize a copy of the ConnectedThread
        synchronized (this) {
            if (mState != STATE_CONNECTED) return;
            r = mConnectedThread;
        }
        // Perform the write unsynchronized
        r.write(out);
    }

    /**
     * Indicate that the connection attempt failed and notify the UI Activity.
     */
    private void connectionFailed() {
        // Send a failure message back to the Activity
        Message msg = mHandler.obtainMessage(BluetoothChat.MESSAGE_TOAST);
        Bundle bundle = new Bundle();
        bundle.putString(BluetoothChat.TOAST, "Unable to connect device");
        msg.setData(bundle);
        mHandler.sendMessage(msg);

        // Start the service over to restart listening mode
        BluetoothChatService.this.start();
    }

    /**
     * Indicate that the connection was lost and notify the UI Activity.
     */
    private void connectionLost() {
        // Send a failure message back to the Activity
        Message msg = mHandler.obtainMessage(BluetoothChat.MESSAGE_TOAST);
        Bundle bundle = new Bundle();
        bundle.putString(BluetoothChat.TOAST, "Device connection was lost");
        msg.setData(bundle);
        mHandler.sendMessage(msg);

        // Start the service over to restart listening mode
        BluetoothChatService.this.start();
    }

    /**
     * This thread runs while listening for incoming connections. It behaves
     * like a server-side client. It runs until a connection is accepted
     * (or until cancelled).
     */
    private class AcceptThread extends Thread {
        // The local server socket
        private final BluetoothServerSocket mmServerSocket;
        private String mSocketType;

        public AcceptThread(boolean secure) {
            BluetoothServerSocket tmp = null;
            mSocketType = secure ? "Secure":"Insecure";

            // Create a new listening server socket
            try {
                if (secure) {
                    tmp = mAdapter.listenUsingRfcommWithServiceRecord(NAME_SECURE,
                        MY_UUID_SECURE);
                } else {
                    tmp = mAdapter.listenUsingInsecureRfcommWithServiceRecord(
                            NAME_INSECURE, MY_UUID_INSECURE);
                }
            } catch (IOException e) {
                Log.e(TAG, "Socket Type: " + mSocketType + "listen() failed", e);
            }
            mmServerSocket = tmp;
        }

        public void run() {
            if (D) Log.d(TAG, "Socket Type: " + mSocketType +
                    "BEGIN mAcceptThread" + this);
            setName("AcceptThread" + mSocketType);

            BluetoothSocket socket = null;

            // Listen to the server socket if we're not connected
            while (mState != STATE_CONNECTED) {
                try {
                    // This is a blocking call and will only return on a
                    // successful connection or an exception
                    socket = mmServerSocket.accept();
                } catch (IOException e) {
                    Log.e(TAG, "Socket Type: " + mSocketType + "accept() failed", e);
                    break;
                }

                // If a connection was accepted
                if (socket != null) {
                    synchronized (BluetoothChatService.this) {
                        switch (mState) {
                        case STATE_LISTEN:
                        case STATE_CONNECTING:
                            // Situation normal. Start the connected thread.
                            connected(socket, socket.getRemoteDevice(),
                                    mSocketType);
                            break;
                        case STATE_NONE:
                        case STATE_CONNECTED:
                            // Either not ready or already connected. Terminate new socket.
                            try {
                                socket.close();
                            } catch (IOException e) {
                                Log.e(TAG, "Could not close unwanted socket", e);
                            }
                            break;
                        }
                    }
                }
            }
            if (D) Log.i(TAG, "END mAcceptThread, socket Type: " + mSocketType);

        }

        public void cancel() {
            if (D) Log.d(TAG, "Socket Type" + mSocketType + "cancel " + this);
            try {
                mmServerSocket.close();
            } catch (IOException e) {
                Log.e(TAG, "Socket Type" + mSocketType + "close() of server failed", e);
            }
        }
    }


    /**
     * This thread runs while attempting to make an outgoing connection
     * with a device. It runs straight through; the connection either
     * succeeds or fails.
     */
    private class ConnectThread extends Thread {
        private final BluetoothSocket mmSocket;
        private final BluetoothDevice mmDevice;
        private String mSocketType;

        public ConnectThread(BluetoothDevice device, boolean secure) {
            mmDevice = device;
            BluetoothSocket tmp = null;
            mSocketType = secure ? "Secure" : "Insecure";

            // Get a BluetoothSocket for a connection with the
            // given BluetoothDevice
            try {
                if (secure) {
                    tmp = device.createRfcommSocketToServiceRecord(
                            MY_UUID_SECURE);
                } else {
                    tmp = device.createInsecureRfcommSocketToServiceRecord(
                            MY_UUID_INSECURE);
                }
            } catch (IOException e) {
                Log.e(TAG, "Socket Type: " + mSocketType + "create() failed", e);
            }
            mmSocket = tmp;
        }

        public void run() {
            Log.i(TAG, "BEGIN mConnectThread SocketType:" + mSocketType);
            setName("ConnectThread" + mSocketType);

            // Always cancel discovery because it will slow down a connection
            mAdapter.cancelDiscovery();

            // Make a connection to the BluetoothSocket
            try {
                // This is a blocking call and will only return on a
                // successful connection or an exception
                mmSocket.connect();
            } catch (IOException e) {
                // Close the socket
                try {
                    mmSocket

字符被正确回显的事实可能表明波特率设置正确并且设备正在看到您想要的字符。不过,听起来设备仍然没有看到正确终止的请求字符串(以回车符结尾的请求字符串)。

我提到这一点是因为您注意到附加“/r”,它与“\r”(CR 字符)不同。例如,在 Java 中:

OutputStream out;

String correct = "ATRV\r";
//This line will correctly write 5 bytes (in hex): 41 54 52 56 0D
out.write(correct.getBytes());

String incorrect = "ATRV/r";
//This line will incorrectly write 6 bytes (in hex): 41 54 52 56 2F 72
out.write(incorrect.getBytes());

0x0D 字符是 ELM327 正在寻找的终止 AT 命令并解析它的字符。

Edit:

如果您使用键盘在示例应用程序中手动键入字符“atrv\r”,则存在相同的问题。文本被解释为 6 个唯一字母(即“A”、“T”、“R”、“V”、“\”和“r”或十六进制41 54 52 56 5C 72) 并且 '\r' 不被解释为单个 CR 字符。

您可能无法从示例代码中执行此操作,除非您添加一些特殊代码来解析带有“\”的组合并将其替换为特殊字符值。更好的解决方案是修改示例代码,以便在按下发送按钮时始终将 '\r' 字符附加到您键入的任何内容(记住...与简单地添加 '\' 后跟 'r' 不同)您只需在文本框中输入“ATRV”即可。你的里面有这样的东西OnEditorActionListener代码(再次注意斜杠的方向,否则您只需添加两个字符):

public boolean onEditorAction(TextView view, int actionId, KeyEvent event) {
    // If the action is a key-up event on the return key, send the message
    if (actionId == EditorInfo.IME_NULL && event.getAction() == KeyEvent.ACTION_UP) {
        //This gets the raw text from the box
        String message = view.getText().toString();
        //Append a CR to every message sent.  The added string is defined as a literal,
        // so Java parses is as a single CR character.
        sendMessage(message + "\r");
    }
    if(D) Log.i(TAG, "END onEditorAction");
    return true;
}

您还可以通过对字符串命令进行硬编码来修改示例,就像我在上面的示例中所做的那样。 Java 正确解释字符串文字值“ATRV\r”,将该 CR 字符放在末尾(使其成为 5 个字符的字符串)。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用BluetoothChat与ELM327通信 的相关文章

  • APK META-INF/library_release.kotlin_module 中复制的重复文件

    我最近通过 JitPack 添加了两个 Android 库 但出现以下错误 Duplicate files copied in APK META INF library release kotlin module 我已经清除了缓存 并尝试使
  • 如何在 StateListDrawable 中设置可绘制对象的 alpha 值?

    我想在按下时更改可绘制对象的 alpha 值 因此 我创建了两个可绘制对象并将它们放入 StateListDrawable 中 并设置按下状态的 alpha 值 但它就是行不通 StateListDrawable content new S
  • 如何检测android中的颠倒方向?

    在我的 Android 应用程序中 我有全景图像 并且我使用 TYPE ORIENTATION 传感器根据手机运动旋转该图像 它对于横向和纵向都工作良好 这是旋转逻辑的代码 Override public void onSensorChan
  • 服务在后台运行?

    我正在构建的应用程序的功能之一是记录功能 我通过在服务中启动 MediaRecorder 对象来实现此目的 Intent intent new Intent v getContext RecordService class Messenge
  • ActionBarCompat 支持库 android:selectableItemBackground 不起作用

    我正在使用新的 ActionBarCompat 支持库 操作栏中的操作按钮在按下时应更改其背景 它适用于 Android 4 3 但不适用于 Gingerbread 在姜饼中 如果我按下按钮 它不会改变背景 我什至改变了选择器 它再次适用于
  • 如何使用 (a)smack 在 Android 上保持 XMPP 连接稳定?

    我使用适用于 Android 的 asmack android 7 beem 库 我有一个后台服务正在运行 例如我的应用程序保持活动状态 但 XMPP 连接迟早会在没有任何通知的情况下消失 服务器表示客户端仍然在线 但没有发送或接收数据包
  • Android 上通过 JSCH 的基本 SSH 连接

    作为来自此的用户question https stackoverflow com questions 14323661 simple ssh connect with jsch和这个tutorial http eridem net andr
  • Android 上的硬币识别

    我目前正在开发一个 Android 应用程序 它能够拍摄硬币的现有图像 或者使用内置摄像头扫描单个硬币 非常像 Google Goggles 我正在使用 Android 版 OpenCV 我的问题如下 什么方法最适合使用 OpenCV 在
  • 将寻呼机视为列表视图行项目

    我有一个包含 20 行的列表视图 我想为列表视图中的每一行设置一个视图寻呼机 由于列表视图的行中的项目可能是一个或多个 并且我想使用视图分页器显示列表视图行项目 为此 我使用以下代码 将显示在列表视图行中的自定义布局 作为分页器项目
  • 注销时Firebase facebook按钮android身份验证

    我在我的 Android 应用程序中使用 firebase 并在 facebook SDK 中使用登录 我面临的唯一问题是 当我使用 facebook 登录然后注销时 facebook 登录按钮处于 注销 状态 当我单击它时 它会询问我是否
  • 在 Android 中关闭 Spinner 中的下拉菜单

    在 Android 中打开和关闭微调器时 我需要为箭头图标设置动画 打开微调器时我可以旋转箭头 我只是放了一个setOnTouchListener on the Spinner 当下拉菜单关闭或隐藏时 问题就来了 因为我不知道如何在该操作上
  • Android - 内容值覆盖现有行

    我正在尝试使用插入值ContentValues 我已将 5 个值插入到 5 列中 运行应用程序后 我只有最后一组值的行ContentValues 前四组未插入 ContentValues cv new ContentValues cv pu
  • 使用startActivityForResult,如何获取子活动中的requestCode?

    我有四项活动 即 A B C 和 D 我的情况是A将通过startActivityForResult启动活动B startActivityForResult new Intent this B class ONE 在另一种情况下 我将使用不
  • NoClassDefFoundError:com.google.firebase.FirebaseOptions

    我继续得到NoClassDefFoundError在我正在使用的其他测试设备 4 4 2 上 但在我的测试设备 Android 5 1 上运行良好 我尝试了用谷歌搜索的解决方案 但似乎没有任何效果 我正在使用 Firebase 实时数据库
  • 如何在Android中隐藏应用程序标题? [关闭]

    Closed 这个问题不符合堆栈溢出指南 help closed questions 目前不接受答案 我想隐藏应用程序标题栏 您可以通过编程来完成 import android app Activity import android os
  • 协程和 Firebase:如何实现类似 Javascript 的 Promise.all()

    在 Javascript 中 您可以同时启动两个 或更多 异步任务 等待它们完成 然后执行某些操作 继续 const firstReturn secondReturn await Promise all firstPromise secon
  • 使用 eclipse 配置mockito 时出现问题。给出错误:java.lang.verifyError

    当我将我的mockito库添加到类路径中 并使用一个简单的mockito示例进行测试时 我尝试使用模拟对象为函数add返回错误的值 我得到java lang verifyerror 以下是用于测试的代码 后面是 logcat Test pu
  • Admob - 没有广告可显示

    你好 我尝试制作一些在 Android 手机上显示广告的示例程序 并尝试在 v2 2 的模拟器上测试它 代码中的一切似乎都很好 但调试器中的 AdListener 表示 响应消息为零或空 onFailedToReceiveAd 没有广告可显
  • TYPE_ACCELEROMETER 和 TYPE_LINEAR_ACCELERATION 传感器有什么区别?

    I think TYPE ACCELEROMETER显示设备加速 但是 我不明白什么时候应该使用TYPE LINEAR ACCELERATION 我需要计算移动设备的速度 哪种传感器适合此应用 另外 我读到TYPE LINEAR ACCEL
  • RecyclerView元素更新+异步网络调用

    我有一个按预期工作的回收视图 我的布局中有一个按钮可以填充列表 该按钮应该进行异步调用 根据结果 我更改按钮的外观 这一切都发生得很好 但是 当我单击按钮并快速向下滚动列表时 异步调用的结果会更新新视图的按钮 代替旧视图的视图 我该如何处理

随机推荐

  • ValueError:类的数量必须大于一(python)

    经过时x y in fit 我收到以下错误 回溯 最近一次调用最后一次 文件 C Classify classifier py 第 95 行 位于 train avg test avg cms train model X y ceps pl
  • 如何识别Python中哪个函数调用引发异常?

    我需要确定谁引发异常来处理更好的 str 错误 有办法吗 看看我的例子 try os mkdir valid created dir os listdir invalid path except OSError msg here i wan
  • 为什么曼彻斯特编码中比特率是波特率的一半?

    我认为波特率是符号的速率 如果每个符号包含n位 那么比特率应该是n x baud rate 在以太网 曼彻斯特编码 中 如果比特率是波特率的一半 那么一个符号包含1 2位 据我所知 比特率至少应该不小于符号率 波特率 关于波特率和比特率的关
  • 如何创建带有类别/细分的列表视图?

    我想在 android 中创建 listview 具有以下场景 标题类别 1 项目 1 第2项 第3项 标题类别 2 项目 1 第2项 标题类别 3 项目 1 等等 有人指导我如何实现这一目标吗 任何帮助 将不胜感激 答案的一部分就在那里
  • 在 Windows 上使用 pip 安装 zbar 失败

    我正在尝试安装zbar在我的 Windows x64 机器上 pip install zbar 这就是我得到的 Collecting zbar Using cached zbar 0 10 tar bz2 Installing collec
  • 如何使用坐标将标记移动 100 米

    我有2个坐标 坐标1是一个 人 坐标2是目的地 如何将坐标 1 移近 100 米以靠近坐标 2 这将在 cron 作业中使用 因此仅包含 php 和 mysql 例如 此人位于 51 26667 3 45417 目的地是 51 575001
  • 如何获取Vine视频地址

    I love vinepeek并想让事情变得更好 我有 Vine 链接 例如http vine co v bJqWrOHjMmU 但是这是页面链接 而不是视频 URL 我知道它是新的 但是 Vine 有 API 或者我怎样才能获取视频的 u
  • 为什么 java.util.Observable 不是抽象类?

    我刚刚注意到 java util Observable 是一个具体的类 由于 Observable 的目的是扩展 这对我来说似乎很奇怪 这样做有什么原因吗 I found 本文上面说 observable 是一个具体的类 因此必须预先确定从
  • 为什么 ftell( stdin ) 会导致非法查找错误

    以下代码输出 非法查找 include
  • Node Js 上的 Axios 不会保留请求服务器上的会话,而 PostMan 会保留

    我可以在 PostMan 上执行以下操作 1 POST方法登录公司服务器 2 以登录用户的身份在公司服务器上发出其他请求 我创建了一个nodejs应用程序来与公司服务器进行通信 我正在使用 axios 库进行上述通信 登录公司服务器后 任何
  • 使用 python xlib 全局捕获、忽略和发送按键事件,识别虚假输入

    我想在普通键盘上实现按键和弦 我想我使用 python xlib 为此 程序必须全局吞下所有关键事件 然后才允许它们通过 我当前的测试只是抓住 1 键 如果按下此键 它将调用一个处理程序 该处理程序通过 xtest fake input 将
  • OpenCV Python 中与多个对象的模板匹配

    我正在尝试使用 opencv python 在图像中查找多个模板 根据这个链接 但问题是 为单个对象返回多个位置略有不同的点 像这样的东西 我不想用cv2 minMaxLoc 因为图像中有多个模板 我写了一个删除平仓头寸的函数 但我想知道这
  • Silverlight 4 - 将 UIElement 渲染为图像

    我有一个UIElement我想捕获用户单击按钮时的快照 当用户单击按钮时 我想采取UIElement并将其当前状态加载到 Image 元素中 我如何渲染UIElement as an Image 假设FrameworkElement你想要渲
  • Smarty 基准测试,有人吗?

    我正在考虑将 Smarty 作为我的 Web 应用程序模板解决方案 现在我担心它相对于普通 PHP 的性能 Smarty 网站说它应该是相同的 但是 我找不到任何人进行真正的基准测试来证明该声明是对还是错 有人做过 Smarty 与普通 P
  • MSVC 大括号初始化与双打似乎违反了标准?

    看看这个简单的程序 int main float f2 7 2 OK with warning float f3 7 199999809265137 OK no warning float f4 7 2 Fails float f5 7 1
  • jQuery ui datepicker向下滚动网页时定位问题

    我有一个使用 jQuery ui 日期选择器的多个实例的网页 我的网页将显示约 80 条记录 这超出了单个屏幕截图的范围 div class recordname div lt additional html here gt 我已将日期选择
  • Android 10:通过 MediaStore 获取带有位置信息的图库

    查看 Android 10 中引入的存储访问更改here 现在默认编辑位置信息 Google 要求我们致电setRequireOriginal 在 MediaStore 对象上 以媒体的 uri 作为参数 当您一张一张地获取媒体时 这是可行
  • 如何每2分钟调用一次函数

    如何在 AngularJS 中每两分钟调用一次保存函数 请帮我 scope save function http url api products method POST data scope product success functio
  • Javascript/HTML5:获取音频标签的当前时间

    我的模板中有一个音频标签 我需要在单击按钮时显示它的当前时间 请检查我下面的代码 var myaudio document getElementsByTagName audio 0 var cur time myaudio currentT
  • 使用BluetoothChat与ELM327通信

    我目前正在尝试通过 BluetoothChat 示例应用程序与 ELM327 OBDII 蓝牙适配器进行通信 我可以连接 因为我更改了 UUID 但是我只能接收启动命令和提示 gt 来发送命令 每当我尝试发送命令时 我都会收到以下信息 CA