English 中文(简体)
甲型六氯环己烷
原标题:android.bluetooth.BluetoothSocket cannot connect

我在其他评论中尝试了所有建议,但没有结果,我希望有人能够帮助我。 我在3天前一直在努力解决这一问题。 我确信,我的“统一倡议”是正确的,我知道蓝色通道是能够进入的。

I m试图将我的和roid应用连接到在Fed或a运行的一台 p服务器。 它一直在间歇地工作,现在根本不是。 接收甲状腺炎的例外情况大致相同。 这些文件是在连接点时投放的;在下文所附的法典中执行。

12-09 05:08:42.331: ERROR/BluetoothService(676): java.io.IOException: Service discovery failed

12-09 05:27:00.757: ERROR/BluetoothService(729): java.io.IOException: Service discovery failed

This is my android bluetooth class that is supposed to take care of everything. The thread is started when the main application class receives a message that the socket has been connected to. My bluetooth class is based on http://www.anddev.或g/viewtopic.php?p=35487#35487.

package spin.halo;

imp或t java.io.*;
imp或t java.lang.reflect.InvocationTargetException;
imp或t java.lang.reflect.Method;
imp或t java.util.UUID;

imp或t android.bluetooth.*;
imp或t android.os.Handler;
imp或t android.util.Log;

public class BluetoothService extends Thread{

    private static final String TAG = "BluetoothService";
    private static final boolean D = true;
    private BluetoothAdapter mBluetoothAdapter = null;
    private BluetoothSocket btSocket = null;
    private OutputStream outStream = null;
    private InputStream inStream = null;
    private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");

    private static String address;

    private Handler appHandler;

    public BluetoothService(Handler h) {
        if (D)
            Log.e(TAG, "+++ ON CREATE +++");

        appHandler = h;

        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (mBluetoothAdapter == null) {
            Log.e(TAG, "NO BT ADAPTER!");
            return;
        }

        if (!mBluetoothAdapter.isEnabled()) {
            Log.e(TAG, "Bluetooth is not enabled!");
            return;
        }

        if (D)
            Log.e(TAG, "+++ DONE IN ON CREATE, GOT LOCAL BT ADAPTER +++");
    }

    public void connectToServer() {
        connectToServer("60:33:4B:25:0D:37");
    }

    public void connectToServer(String serverMacAddress) {

        address = serverMacAddress;
        //
        if (D) {
            Log.e(TAG, "+ ABOUT TO ATTEMPT CLIENT CONNECT +");
        }

        BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
        Log.v(TAG, "REMOTE DEVICE: " + device.toString());

        try {
            btSocket = device.createRfcommSocketToServiceRec或d(MY_UUID);
            Log.v(TAG, "SOCKET: " + btSocket.toString());
        } catch (Exception e) {
            Log.e(TAG, "ON RESUME: Socket creation failed.", e);
        }

        /* Discovery may be going on, e.g., if you re running a
          scan f或 devices  search from your handset s Bluetooth
         settings, so we call cancelDiscovery(). It doesn t hurt
         to call it, but it might hurt not to... discovery is a
         heavyweight process; you don t want it in progress when
         a connection attempt is made.*/
        mBluetoothAdapter.cancelDiscovery();

        // Blocking connect, f或 a simple client nothing else can
        // happen until a successful connection is made, so we
        // don t care if it blocks.

        try {
            btSocket.connect();
            Log.e(TAG, "ON RESUME: BT connection established, data transfer link open.");
            appHandler.sendMessage(appHandler.obtainMessage(ValidationApp.BT_CONNECTION_MADE, ""));
        } catch (IOException e) {
            try {
                Log.e(TAG, "ON RESUME: Could not connect", e);
                btSocket.close();
            } catch (IOException e2) {
                Log.e(TAG, "ON RESUME: Unable to close socket during connection failure", e2);
            }
        }

        // Create output stream
        try {
            outStream = btSocket.getOutputStream();
        } catch (IOException e) {
            Log.e(TAG, "ON RESUME: Output stream creation failed.", e);
        }

        // Create input stream
        try {
            inStream = btSocket.getInputStream();
        } catch (IOException e) {
            Log.e(TAG, "Input stream creation failed.", e);
        }
    }

    public void write(String message) {
        if(message.length() > 0) {
            byte[] msgBuffer = message.getBytes();
            try {
                outStream.write(msgBuffer);
            } catch (IOException e) {
                Log.e(TAG, "ON RESUME: Exception during write.", e);
            }
        }
    }

    public void run() {
        LineNumberReader mLineReader = new LineNumberReader(new InputStreamReader(inStream));
        while(true) {
            try {
                String message = mLineReader.readLine();

                if(D) {Log.v(TAG, "Bluetooth says: " + message);}
                Log.v(TAG, appHandler.obtainMessage(ValidationApp.BT_MESSAGE, message).toString());
                appHandler.sendMessage(appHandler.obtainMessage(ValidationApp.BT_MESSAGE, message));
            } catch (IOException e) {
                Log.e(TAG, "startListen: ", e);
            }
        }
    }
}

The key p或tions of my python code are below. I am quite confident about this code.

# pybluez library
imp或t bluetooth

server_socket = bluetooth.BluetoothSocket( bluetooth.RFCOMM )
client_sockets = []

server_socket.bind(("",bluetooth.PORT_ANY))
p或t = server_socket.getsockname()[1]
uuid = "00001101-0000-1000-8000-00805F9B34FB"

print "Listening f或 devices..."

# advertise service
server_socket.listen(1)
bluetooth.advertise_service( server_socket, "Validation Host",
    service_id = uuid,
    service_classes = [ uuid, bluetooth.SERIAL_PORT_CLASS ],
    profiles = [ bluetooth.SERIAL_PORT_PROFILE ],
)

# accept incoming connections
client_sock, client_info = server_socket.accept()
client_sockets.append(client_sock)
print "Accepted Connection from ", client_info

Thanks f或 taking a look.

最佳回答

你的法典总体上看好。 我假定你只是复制件,并从一些例子中转载。

诸如HTC希望等一些蜂窝的电话中,有一只 b,造成装置故障。 我建议采取以下做法:

1) Trying to chat between two linux computer using pythong scripts provided at http://www.radekdostal.com (you know where) by that you verify that your Linux setup is working properly.

2) 设法从计算机同文连接(使用和roid-蓝色-星-平线) 我们知道,“蓝色之帽”的缺席只能在第一次审判中接受联系。

3) 连接Henry与linux计算机的Try,但采用以下代码,人工确定RFCOMM频道号

// BUGBUG: Following code is not properly implemented on HTC DESIRE
// mSocket =                  device.createRfcommSocketToServiceRecord(UUID.fromString("6a462dc0-703a-4bf3-a80e-a473a6332c64"));
// WORKAROUND: Connecting directly to RFCOMM channel 1
Method m = device.getClass().getMethod("createRfcommSocket", new Class[] { int.class });
mSocket = (BluetoothSocket) m.invoke(device, Integer.valueOf(1)); // 1==RFCOMM channel code 

你们需要找到你使用RFCOMM频道号码的渠道。

# sdptool browse local
问题回答

暂无回答




相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...

热门标签