与OBD端口的Android蓝牙连接

时间:2017-04-24 16:40:48

标签: android bluetooth

我正在做一个通过OBD 2端口与汽车通信的应用程序。 现在我正在使用蓝牙连接,我正在阅读Android文档,并且有关于与obd设备的连接和通信的一些问题。

我像这样的步骤: 1)如果蓝牙未激活,请激活蓝牙 2)搜索设备并显示在列表中 3)在列表视图中的OnItemClick用于连接具有客户端蓝牙连接的已触摸设备(已创建)

这里我有一些问题需要了解Android文档......

对于与设备的连接,我使用此代码(如文档)

foundedDeviceList.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> adapter, View view,
                                    final int position, long id) {

                mBluetoothAdapter.cancelDiscovery();

                String deviceName = (String)adapter.getItemAtPosition(position);

                Toast.makeText(getApplicationContext(), "Selezionato: " + deviceName,
                        Toast.LENGTH_LONG).show();

                for(BluetoothDevice dv : deviceList){
                    if(dv.getName() != null && dv.getName().equals(deviceName)){
                        selectedDevice = dv;
                    }
                }

                ConnectThread connectThread = new ConnectThread(selectedDevice);
                connectThread.run();


            }
        });

   //Thread of bluetooth connection
    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;

            try {
                // Get a BluetoothSocket to connect with the given BluetoothDevice.
                // MY_UUID is the app's UUID string, also used in the server code.
                tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
                Log.i(TAG, "Socket's create() successfull");
            } catch (IOException e) {
                Log.e(TAG, "Socket's create() method failed", e);
            }
            mmSocket = tmp;
        }



        public void run() {
            // Cancel discovery because it otherwise slows down the connection.
            mBluetoothAdapter.cancelDiscovery();
            Log.i(TAG, "run() eseguito");

            try {
                // Connect to the remote device through the socket. This call blocks
                // until it succeeds or throws an exception.
                mmSocket.connect();
            } catch (IOException connectException) {
                // Unable to connect; close the socket and return.
                try {
                    mmSocket.close();
                } catch (IOException closeException) {
                    Log.e(TAG, "Could not close the client socket", closeException);
                }
                return;
            }

            // The connection attempt succeeded. Perform work associated with
            // the connection in a separate thread.
            //manageMyConnectedSocket(mmSocket);
        }

        // Closes the client socket and causes the thread to finish.
        public void cancel() {
            Log.i(TAG, "cancel() eseguito");
            try {
                mmSocket.close();
            } catch (IOException e) {
                Log.e(TAG, "Could not close the client socket", e);
            }
        }
    }

我不确定connectThread.run()他们没有解释ConnectThread中方法的用法,我不知道如何声明manageMyConnectedSocket(mmSocket);

为了通信我创建了一个类MyBluetoothService.java和类似文档我写这段代码:

package com.tesi.ddz.obd_project;

import android.bluetooth.BluetoothSocket;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * Created by ddz on 24/04/17.
 */

public class MyBluetoothService{

    private static final String TAG = "MY_APP_DEBUG_TAG";
    private Handler mHandler; // handler that gets info from Bluetooth service

    // Defines several constants used when transmitting messages between the
    // service and the UI.
    private interface MessageConstants {
        public static final int MESSAGE_READ = 0;
        public static final int MESSAGE_WRITE = 1;
        public static final int MESSAGE_TOAST = 2;

        // ... (Add other message types here as needed.)
    }

    private class ConnectedThread extends Thread {
        private final BluetoothSocket mmSocket;
        private final InputStream mmInStream;
        private final OutputStream mmOutStream;
        private byte[] mmBuffer; // mmBuffer store for the stream

        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();
            } catch (IOException e) {
                Log.e(TAG, "Error occurred when creating input stream", e);
            }
            try {
                tmpOut = socket.getOutputStream();
            } catch (IOException e) {
                Log.e(TAG, "Error occurred when creating output stream", e);
            }

            mmInStream = tmpIn;
            mmOutStream = tmpOut;
        }

        public void run() {
            mmBuffer = new byte[1024];
            int numBytes; // bytes returned from read()

            // Keep listening to the InputStream until an exception occurs.
            while (true) {
                try {
                    // Read from the InputStream.
                    numBytes = mmInStream.read(mmBuffer);
                    // Send the obtained bytes to the UI activity.
                    Message readMsg = mHandler.obtainMessage(
                            MessageConstants.MESSAGE_READ, numBytes, -1,
                            mmBuffer);
                    readMsg.sendToTarget();
                } catch (IOException e) {
                    Log.d(TAG, "Input stream was disconnected", e);
                    break;
                }
            }
        }

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

                // Share the sent message with the UI activity.
                Message writtenMsg = mHandler.obtainMessage(
                        MessageConstants.MESSAGE_WRITE, -1, -1, mmBuffer);
                writtenMsg.sendToTarget();
            } catch (IOException e) {
                Log.e(TAG, "Error occurred when sending data", e);

                // Send a failure message back to the activity.
                Message writeErrorMsg =
                        mHandler.obtainMessage(MessageConstants.MESSAGE_TOAST);
                Bundle bundle = new Bundle();
                bundle.putString("toast",
                        "Couldn't send data to the other device");
                writeErrorMsg.setData(bundle);
                mHandler.sendMessage(writeErrorMsg);
            }
        }

        // Call this method from the main activity to shut down the connection.
        public void cancel() {
            try {
                mmSocket.close();
            } catch (IOException e) {
                Log.e(TAG, "Could not close the connect socket", e);
            }
        }
    }
}

我会通过调用类manageMyConnectedSocket(mmSocket);来实现方法MyBluetoothService.java,并在理解文档的同时管理连接....

他们将ConnectedThread声明为私有,因此我无法在MainActivity.java中调用此方法....那么实现此连接的最佳方法是什么? 不要使用MyBluetoothService并向MainActivity声明all或继续这样工作,并且可能声明ConnectedThred是公共的,以便我可以在MainActivity中使用它?

特别是我不明白如何使用课程MyBluetoothService.java和方法manageMyConnectionSocket(mmsocket)

0 个答案:

没有答案