带有动态OBD命令的Android共享阵列

时间:2017-08-18 10:25:26

标签: android multithreading arraylist bluetooth obd-ii

在我的应用程序中,我通过OBD端口和蓝牙建立了与汽车的通信。 我有SharedPreferences,其中包含由Preference Activity设置的命令首选项。

我想使用可以动态更改其内容的命令的共享阵列,并将新的ArrayList发送到管理通信的线程。

有一些方法可以做到这一点或只是使用SharedPreferences,当更改数组的内容时,我重新启动管理与设备通信的线程。

我需要一些可以更改的内容(添加或删除ArrayList中的命令),同时通知线程发送ArrayList已更改项目的命令。

管理连接的方法

   private synchronized void manage() {
        Log.d(TAG, "connected, Socket Type:");

        // 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 any thread currently managing connections
        if (mManageThread != null) {
            mManageThread.cancel();
            mManageThread = null;
        }

        if (mmSocket != null && mmDevice != null) {
            // Start the thread to manage the connection and perform transmissions
            mManageThread = new ManageDataThread(mmSocket);
            mManageThread.start();

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

管理连接和消息交换的线程mManageThread

   public class ManageDataThread extends Thread {

        private final BluetoothSocket mmSocket;
        private final InputStream mmInStream;
        private final OutputStream mmOutStream;
        private boolean wait_response = false;
        private String typeCommand;

        public ManageDataThread(BluetoothSocket socket) {
            Log.d(TAG, "create ManageDataThread: ");

            mmSocket = socket;
            InputStream tmpIn = null;
            OutputStream tmpOut = null;

            // Get the BluetoothSocket input and output streams
            try {
                tmpIn = socket.getInputStream();
                tmpOut = socket.getOutputStream();
            } catch (IOException e) {
                Log.e(TAG, "temp sockets not created", e);
            }

            mmInStream = tmpIn;
            mmOutStream = tmpOut;
            mState = STATE_CONNECTED;

        }

        public void run() {

            ObdCommand obc = new ObdCommand();

            while(canGo) {
                for (final String command : commandArray) {

                    byte[] send = command.getBytes();
                    write(send); //Setta la wait_response come true
                    //mState = STATE_WAIT_RESPONSE;

                    byte[] buffer = new byte[1024];
                    int bytes;

                    // Keep listening to the InputStream while connected
                    while (wait_response) {
                        try {
                            // Read from the InputStream
                            bytes = mmInStream.read(buffer);

                            obc.readResult(mmInStream);

                            //formattedMessage = obc.getResult();
                            formattedMessage = obc.getCalculatedResult();
                            //Ritorno la ripologia di comando
                            typeCommand = obc.getCommandType();
                            //buffer = (byte) obc.getBuffer();

                            // Send the obtained bytes to the UI Activity
                            /*mHandler.obtainMessage(Constants.MESSAGE_READ, bytes, -1, formattedMessage)
                                    .sendToTarget();*/

                            mHandler.obtainMessage(Constants.MESSAGE_READ, bytes, -1, typeCommand
                                    + ""
                                    + formattedMessage)
                                    .sendToTarget();

                            wait_response = false;

                        } catch (IOException e) {
                            Log.e(TAG, "disconnected", e);
                            connectionLost();
                            break;
                        }
                    }


                }

                try {
                    ManageDataThread.sleep(400);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

            }



        }

        /**
         * Write to the connected OutStream.
         *
         * @param buffer The bytes to write
         */
        public void write(byte[] buffer) {
            try {
                mmOutStream.write(buffer);

                // Share the sent message back to the UI Activity
                mHandler.obtainMessage(Constants.MESSAGE_WRITE, -1, -1, buffer)
                        .sendToTarget();
                wait_response = true;
            } catch (IOException e) {
                Log.e(TAG, "Exception during write", e);
                canGo = false;
            }
        }

        public void cancel() {
            try {
                canGo = false;
                mmSocket.close();
            } catch (IOException e) {
                Log.e(TAG, "close() of connect socket failed", e);
            }
        }
    }

这里我不能使用一些方法来检查是否更改了数组并更改了线程中的命令列表? 唯一的方法是停止和重启方法吗?

这里是MainActivity中的调用

   @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
        setSupportActionBar(myToolbar);

        rpmTxt = (TextView) findViewById(R.id.rpmText);
        speedTxt = (TextView) findViewById(R.id.speedText);
        coolantTxt = (TextView) findViewById(R.id.colantTempText);
        carbTxt = (TextView) findViewById(R.id.carbTypeText);
        nodata = (TextView) findViewById(R.id.nodataTxt);
        canerror = (TextView) findViewById(R.id.canErrorTxt);

        /**
         * SharedPreferences per gestire quali cose mostrare nell'activity
         */
        showUserSettings();

        /*Check bluetooth sensor*/
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (mBluetoothAdapter == null) {
            // Device does not support Bluetooth
            Toast.makeText(getApplicationContext(), "Il telefono NON supporta il bluetooth",
                    Toast.LENGTH_LONG).show();

        }

        // 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 (mBluetoothService == null) {
            setupChat();
        }

    }

和在MyBluetoothService.java中调用Threads的setupchat()方法

 /**
     * Set up the UI and background operations for chat.
     */
    private void setupChat() {
        Log.d(TAG, "setupChat()");

        // Initialize the BluetoothChatService to perform bluetooth connections
        mBluetoothService = new MyBluetoothService(MainActivity.this, mHandler, commandArray);

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

将commandArray读取从sharedPreferences读取到启动Threads的类

0 个答案:

没有答案