簡體   English   中英

兩個設備之間的藍牙數據傳輸不起作用

[英]Bluetooth data transfer between two devices not working

我正在嘗試在兩個設備之間建立藍牙連接,但到目前為止,我還無法使其工作。
自動取款機我在兩部手機上有一個應用程序,根據藍牙地址,一個應發送信息,而另一個應接收信息。

我希望它像這樣工作:在接收器手機上打開應用程序,它將等待並監聽直到發生某些事情,然后在發送器手機上打開應用程序,該應用程序將連接到接收器並發送消息。

注意:該應用程序當前在一部手機上運行Android 5,在另一部手機上運行4.3。

更新:在SeahawksRdaBest的幫助下,我嘗試了一些新的東西,現在遇到了新的錯誤,因此這里是新的代碼和日志:

package com.example.xxxxx;


import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.UUID;

import android.annotation.TargetApi;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;


@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1)
public class BluetoothClass extends Fragment{
    BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    BluetoothDevice selectedDevice;

    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("8ce255c0-200a-11e0-ac64-0800200c9a66");
    public byte[] completeData;
    double totalDistance = 0;
    int wheelRotations=0;

    private static final String address = "00:EE:BD:D1:66:45"; // Phone 1
    private static final String address2 = "18:E2:C2:31:08:AC"; // Phone 2
    private static final String TAG = "BTLOG";

    Handler mHandler = new Handler(){           
        public void handleMessage(Message msg){
            super.handleMessage(msg);
            switch(msg.what){
                case SUCCESS_CONNECT:
                    Log.i(TAG, "CONNECTED");
                    break;

                case MESSAGE_READ:
                    byte[] readBuf = (byte[])msg.obj;
                    Log.v(TAG, "READING: "+readBuf.toString());
            }
        }       
    };

    public void onCreate(Bundle savedInstance){
        super.onCreate(savedInstance);
    }

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
        View rootview = inflater.inflate(R.layout.bluetooth, container,false);      

        rootview.findViewById(R.id.connectDevice).setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                BluetoothDevice selectedDevice = null;

                // If hardcoded device 1, then connect to device 2, or other way around
                if (mBluetoothAdapter.getAddress().equals(address)) {
                    selectedDevice = selectedDevice(address2);
                }
                else if (mBluetoothAdapter.getAddress().equals(address2)) {
                    selectedDevice = selectedDevice(address);
                }
                mBluetoothAdapter.cancelDiscovery();
                ConnectThread ct = new ConnectThread(selectedDevice);
                ct.start();
            }
        });     
        return rootview;
    }   

    public void onActivityCreared(Bundle savedInstanceState){
        super.onActivityCreated(savedInstanceState);
    }

    public void onStart(){
        super.onStart();
    }       

    public void onResume(){
        super.onStart();    
    }

    public void onStop(){
        super.onStart();
    }

    // Get bluetooth device from known address
    public BluetoothDevice selectedDevice(String deviceAddress){
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        BluetoothDevice device;     
        device = mBluetoothAdapter.getRemoteDevice(deviceAddress);
        return device;
    }

    public class ConnectThread extends Thread {
        private final BluetoothSocket mmSocket;
        private BluetoothSocket tmp;
        private final BluetoothDevice mmDevice;

        public ConnectThread(BluetoothDevice device) {
            mmDevice = device;

            try {
                tmp = mmDevice.createRfcommSocketToServiceRecord(MY_UUID);
            } catch (IOException e) {
                Log.e(TAG, "Failed to create temporary socket");
                e.printStackTrace();
            }

            mmSocket = tmp;
            Log.i(TAG, "Finished creating socket");
        }

        public void run() {
            mBluetoothAdapter.cancelDiscovery();

            Log.i(TAG, "Connecting through socket");
            try {
                mmSocket.connect();
            } catch (IOException connectException) {
                Log.e(TAG, "Connection through socket failed: "+connectException);
                Log.i(TAG, "Trying fallback method");

                try {
                    // fallback method for android >= 4.2
                    tmp = (BluetoothSocket) mmDevice.getClass().getMethod("createRfcommSocket", new Class[] {int.class}).invoke(mmDevice,1);
                } catch (IllegalAccessException e) {
                    Log.e(TAG, "Failed to create fallback Illegal Access: "+e);
                    return;
                } catch (IllegalArgumentException e) {
                    Log.e(TAG, "Failed to create fallback Illegal Argument: "+e);
                    return;
                } catch (InvocationTargetException e) {
                    Log.e(TAG, "Failed to create fallback Invocation Target"+e);
                    return;
                } catch (NoSuchMethodException e) {
                    Log.e(TAG, "Failed to create fallback No Such Method"+e);
                    return;
                }

                try {
                    // linked to tmp, so basicly a new socket
                    mmSocket.connect();
                } catch (IOException e) {
                    Log.e(TAG, "Failed to connect with fallback socket: "+e);
                    return;
                }

                Log.i(TAG, "Succesfully connected with fallback socket");
                mHandler.obtainMessage(SUCCESS_CONNECT, mmSocket).sendToTarget();
                return;
            }
            Log.i(TAG, "Succesfully connected with original socket");
                mHandler.obtainMessage(SUCCESS_CONNECT, mmSocket).sendToTarget();

        }       
    }

}

LogCat日志:

11-23 14:03:56.281: I/BTLOG(12107): Finished creating socket
11-23 14:03:56.281: I/BTLOG(12107): Connecting through socket
11-23 14:03:56.286: D/BluetoothUtils(12107): isSocketAllowedBySecurityPolicy start : device null
11-23 14:03:56.286: W/BluetoothAdapter(12107): getBluetoothService() called with no BluetoothManagerCallback
11-23 14:03:59.696: E/BTLOG(12107): Connection through socket failed: java.io.IOException: read failed, socket might closed or timeout, read ret: -1
11-23 14:03:59.696: I/BTLOG(12107): Trying fallback method
11-23 14:03:59.701: D/BluetoothUtils(12107): isSocketAllowedBySecurityPolicy start : device null
11-23 14:03:59.701: W/BluetoothAdapter(12107): getBluetoothService() called with no BluetoothManagerCallback
11-23 14:03:59.761: E/BTLOG(12107): Failed to connect with fallback socket: java.io.IOException: read failed, socket might closed or timeout, read ret: -1

潛在的問題是您沒有對重復的消息使用任何類型的“處理程序”。 您需要一個處理程序對象來始終處理傳入的流,否則您將遇到套接字關閉問題。

這是我的意思:

/*
 * Bluetooth Connection Threads
 */

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(getActivity(), "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
            // This is app specific your logic here
            // Pass Handler Looper here 
                mHandler.obtainMessage(MESSAGE_READ, 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) { }
    }
}

處理程序:

/*
 * Bluetooth Handler Method
 */
    ConnectedThread connectedThread;
    Handler mHandler = new Handler(){           
        public void handleMessage(Message msg){
            super.handleMessage(msg);
            switch(msg.what){
                case SUCCESS_CONNECT:
                    // Do Something;
                    Toast.makeText(getActivity(),"CONNECTED",Toast.LENGTH_SHORT).show();
                    /*
                     * For loop for test values
                     */
                    connectedThread = new ConnectedThread((BluetoothSocket)msg.obj);
                    listView.setVisibility(View.GONE);
                    connectedThread.start();
                    break;

                case MESSAGE_READ:
                // What to do with app specific data handling?? 
            }
        }       
    };

查看我的github以獲取有效的藍牙示例。### Update ###

更新

好了,有幾件事,

首先,我認為您不需要像我一樣使用片段。 我需要多個活動相互交流,而您的項目可能只需要一個活動。 (您仍然可以使用片段的概念,但是請確保您的調用活動正確地調用了片段)。 這里查看我的答案以獲取有關片段的更多信息。

現在,您完全了解藍牙通信的工作原理嗎? 要了解這一點,請閱讀有關Java 線程的信息 因為那就是上面的代碼所基於的。

因此,如果您仔細閱讀日志告訴您的日志,則您正在嘗試連接NULL設備。 顯然你不能那樣做。 請記住,您必須將藍牙設備對象傳遞給ConnectThread。 我相信這就是您的問題所在。 您沒有正確解析地址。 傳遞正確地址的最佳方法是將兩部電話配對。 配對后,您可以從電話存儲器中提取正確格式的地址,並將其傳遞給連接管理器。

嘗試這個:

//Define a Set, which is a unique list (don't forget to initialize it!)
Set<BluetoothDevice> pairedDevices;

在onCreateView()中,

public void onCreateView(..){
  pairedDevices = mBluetoothAdapter.getBondedDevices();
  // Your additional code //
  /*Now you have a set containing the correct address of the paired devices to your phone, 
    I would recommend unpair all devices except the one you are concered with this makes life easier 
    as then you know the first (& only) device in the pairedDevice array is the one you want to                
    connect with.
  */  
  // Now simply pass the Set item to your ConnectThread
  ConnectThread ct = new ConnectThread(pairedDevices[0])
  ct.start();
}

注意

我進行的“選擇設備”方法的結構旨在從ListView中獲取設備地址。 我專門創建了該方法,以便可以看到嘗試連接的設備。 您只是無法復制粘貼代碼並期望它能工作。 確認您的pairedDevice集已填充也是一個好主意。 麻煩您讓您弄清楚如何確認。

暫無
暫無

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

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