簡體   English   中英

如何在多個活動之間保持藍牙連接有效?

[英]How to keep a Bluetooth connection alive across multiple activities?

我在任何地方都找不到我的特定問題的答案。

我需要一種使我的應用程序活動能夠通過藍牙連接分別交換數據的方法。 這是我想做的事情:

我有一個主要活動,上面有一堆按鈕,每個按鈕都啟動一個新活動。 其中一個按鈕應該建立藍牙連接。 創建完成后,我希望能夠返回到主活動,然后單擊另一個按鈕以打開一個新活動,該活動仍可以通過先前創建的藍牙連接發送和接收數據。

我在java / android上還很新,但是我迫切需要幫助,因為我需要為參與其中的團隊項目設置此應用。 目前,我只是從互聯網上收集一些代碼來創建一個應用程序,該應用程序在啟動時僅連接到特定的BT模塊。 但是,如果我無法打開新頁面(活動),則該應用毫無價值。

connectBluetooth和sendReceiveBytes的兩個類都作為線程啟動。 但是我相信這些線程在活動開始時(主要活動)死亡時就會死亡。 因此,如果有任何必要,請賜教。 或者,如果您需要更多信息,請告訴我,我們會為您提供幫助。 謝謝大家!

這是我的代碼:這只是一個單獨的啟動活動,它立即連接到名為“ RNBT-504D”的bt設備。 當我離開應用程序並且活動終止時,由於我的onDestroy方法,該連接已關閉。

我已經展示了廣播接收器,該接收器將啟動連接線程,如果成功,則將啟動管理連接線程(sendReceiveBytes)。 這三個類別均顯示如下。

/* This BroadcastReceiver will display discovered Bluetooth devices */
    public class myOwnBroadcastReceiver extends BroadcastReceiver {
        ConnectToBluetooth connectBT;

        @Override
        public void onReceive(Context context, Intent intent) {
            String action=intent.getAction();

            //Notification that BluetoothDevice is FOUND
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {


                //Gather information about discovered bluetooth device
                BluetoothDevice discoveredDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);


                //Display more information about the discovered device
                if(discoveredDevice.getName().equals("RNBT-504D")){
                    ToastMaster("Device: " + discoveredDevice.getName() +"\n"+ discoveredDevice.getAddress());
                }

                //Connect to the discovered Bluetooth device (SeeedBTSlave)
                if (discoveredDevice.getName().equals("RNBT-504D")) {
                    ToastMaster("Connecting you Now !!");
                    unregisterReceiver(myDiscoverer);
                    connectBT = new ConnectToBluetooth(discoveredDevice);
                    //Connect to the the device in a new thread
                    new Thread(connectBT).start();
                }
            }

            //Notification if bluetooth device is connected
            if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
                ToastMaster("CONNECTED _ YAY");

                while (scSocket==null) {
                    //do nothing
                }
                if (scSocket!=null) {
                    sendReceiveBT = new SendReceiveBytes(scSocket);
                    new Thread(sendReceiveBT).start();
                    //String red = "r";
                    //byte[] myByte = stringToBytesUTFCustom(red);
                    byte[] pronto = new byte[]{0x00, 0x00, 0x00, 0x6E, 0x00, 0x22, 0x00, 0x02, 0x01, 0x56, 0x00, (byte) 0xAC, 0x00, 0x15, 0x00, 0x15, 0x00, 0x15, 0x00, 0x41, 0x00, 0x15, 0x00, 0x41, 0x00, 0x15, 0x00, 0x41, 0x00, 0x15, 0x00, 0x15, 0x00, 0x15, 0x00, 0x41, 0x00, 0x15, 0x00, 0x41, 0x00, 0x15, 0x00, 0x41, 0x00, 0x15, 0x00, 0x41, 0x00, 0x15, 0x00, 0x41, 0x00, 0x15, 0x00, 0x41, 0x00, 0x15, 0x00, 0x15, 0x00, 0x15, 0x00, 0x15, 0x00, 0x15, 0x00, 0x15, 0x00, 0x15, 0x00, 0x15, 0x00, 0x15, 0x00, 0x41, 0x00, 0x15, 0x00, 0x15, 0x00, 0x15, 0x00, 0x41, 0x00, 0x15, 0x00, 0x15, 0x00, 0x15, 0x00, 0x41, 0x00, 0x15, 0x00, 0x15, 0x00, 0x15, 0x00, 0x15, 0x00, 0x15, 0x00, 0x15, 0x00, 0x15, 0x00, 0x15, 0x00, 0x15, 0x00, 0x15, 0x00, 0x15, 0x00, 0x41, 0x00, 0x15, 0x00, 0x41, 0x00, 0x15, 0x00, 0x41, 0x00, 0x15, 0x00, 0x15, 0x00, 0x15, 0x00, 0x41, 0x00, 0x15, 0x00, 0x15, 0x00, 0x15, 0x00, 0x41, 0x00, 0x15, 0x05, (byte) 0x8C, 0x01, 0x56, 0x00, 0x56, 0x00, 0x15, 0x0E, 0x44};
                    sendReceiveBT.write(pronto);
                }
            }

            if(BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)){
                BluetoothDevice discoveredDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                ToastMaster("Disconnected from "+discoveredDevice.getName());
            }
        }
    }

    public static byte[] stringToBytesUTFCustom(String str) {
        char[] buffer = str.toCharArray();
        byte[] b = new byte[buffer.length << 1];
        for (int i = 0; i < buffer.length; i++) {
            int bpos = i << 1;
            b[bpos] = (byte) ((buffer[i]&0xFF00)>>8);
            b[bpos + 1] = (byte) (buffer[i]&0x00FF);
        }
        return b;
    }

    public class ConnectToBluetooth implements Runnable {
        private BluetoothDevice btShield;
        private BluetoothSocket mySocket = null;
        private UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");

        public ConnectToBluetooth(BluetoothDevice bluetoothShield) {
            btShield = bluetoothShield;
            try {
                mySocket = btShield.createRfcommSocketToServiceRecord(uuid);
            }
            catch(IOException createSocketException) {
                //Problem with creating a socket
                Log.e("ConnectToBluetooth", "Error with Socket");
            }
        }

        @Override
        public void run() {
            /* Cancel discovery on Bluetooth Adapter to prevent slow connection */
            bluetooth.cancelDiscovery();

            try {
                /*Connect to the bluetoothShield through the Socket. This will block
           until it succeeds or throws an IOException */
                mySocket.connect();
                scSocket=mySocket;
            } 
            catch (IOException connectException) {
                Log.e("ConnectToBluetooth", "Error with Socket Connection");
                try {
                    mySocket.close(); //try to close the socket
                }
                catch(IOException closeException) {
                }
                return;
            }
        }

        /* Will cancel an in-progress connection, and close the socket */
        public void cancel() {
            try {
                mySocket.close();
            } 
            catch (IOException e) {
            }
        }
    }


    private class SendReceiveBytes implements Runnable {
        private BluetoothSocket btSocket;
        private InputStream btInputStream = null;
        private OutputStream btOutputStream = null;
        String TAG = "SendReceiveBytes";

        public SendReceiveBytes(BluetoothSocket socket) {
            btSocket = socket;
            try {
                btInputStream = btSocket.getInputStream();
                btOutputStream = btSocket.getOutputStream();
            } 
            catch (IOException streamError) { 
                Log.e(TAG, "Error when getting input or output Stream");
            }
        }


        public void run() {
            byte[] buffer = new byte[1024]; // 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
                    bytes = btInputStream.read(buffer);
                    // Send the obtained bytes to the UI activity
                    mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer).sendToTarget();
                } 
                catch (IOException e) {
                    Log.e(TAG, "Error reading from btInputStream");
                    break;
                }
            }
        }


        /* Call this from the main activity to send data to the remote device */
        public void write(byte[] bytes) {
            try {
                btOutputStream.write(bytes);
            } 
            catch (IOException e) { 
                Log.e(TAG, "Error when writing to btOutputStream");
            }
        }


        /* Call this from the main activity to shutdown the connection */
        public void cancel() {
            try {
                btSocket.close();
            } 
            catch (IOException e) { 
                Log.e(TAG, "Error when closing the btSocket");
            }
        }
    }

基本上,您需要在您的主要活動中將BluetoothDevice discoveredDevice聲明為一個字段。 實例化其他活動時,將此作為參數傳遞。

一種可能不是最佳解決方案的方法是在本機層創建一個守護程序來處理BT連接。 由於本機代碼不受Android生命周期管理的限制,因此它會持續一段時間。 因此,您不必擔心活動變為非活動狀態時會取消連接。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM