22

Bluetooth 経由で PC から Android モバイル デバイスに文字列を転送する方法を教えてください。Android モバイル デバイスはサーバーとして機能し、デバイスの画面に文字列メッセージを表示する必要があります。クライアントである PC は、文字列をモバイル デバイスに送信する必要があります。

抽出された文字列(Bluetooth経由で転送)にサーバーが反応するようにします。つまり、一方のサーバーは新しい文字列の到着を常にリッスンする必要がありますが、もう一方の側ではこれらのメッセージに反応できる必要があります (たとえば、あるメニューから別のメニューに移動するなど)。

BlueCove (2.1.1) を BluetoothStack (ライブラリとして BlueCove の jar を両方のプロジェクトに追加) として使用し、ここで見つけたサーバーとクライアントの通信の例と組み合わせて試してみました。

アップデート:

サーバーへの接続を使用したuser_CCのおかげで、サーバーからのコードが更新されました。RFComm

public class RFCommServer extends Thread{

//based on java.util.UUID
private static UUID MY_UUID = UUID.fromString("446118f0-8b1e-11e2-9e96-0800200c9a66");

// The local server socket
private BluetoothServerSocket mmServerSocket;

// based on android.bluetooth.BluetoothAdapter
private BluetoothAdapter mAdapter;
private BluetoothDevice remoteDevice;

private Activity activity;

public RFCommServer(Activity activity) {
    this.activity = activity;
}

public void run() {
    BluetoothSocket socket = null;
    mAdapter = BluetoothAdapter.getDefaultAdapter();        

    // Listen to the server socket if we're not connected
    while (true) {

        try {
            // Create a new listening server socket
            Log.d(this.getName(), ".....Initializing RFCOMM SERVER....");

            // MY_UUID is the UUID you want to use for communication
            mmServerSocket = mAdapter.listenUsingRfcommWithServiceRecord("MyService", MY_UUID);
            //mmServerSocket = mAdapter.listenUsingInsecureRfcommWithServiceRecord(NAME, MY_UUID); // you can also try using In Secure connection...

            // This is a blocking call and will only return on a
            // successful connection or an exception
            socket = mmServerSocket.accept();

        } catch (Exception e) {

        }

        try {
            Log.d(this.getName(), "Closing Server Socket.....");
            mmServerSocket.close();

            InputStream tmpIn = null;
            OutputStream tmpOut = null;

            // Get the BluetoothSocket input and output streams

            tmpIn = socket.getInputStream();
            tmpOut = socket.getOutputStream();

            DataInputStream mmInStream = new DataInputStream(tmpIn);
            DataOutputStream mmOutStream = new DataOutputStream(tmpOut);

            // here you can use the Input Stream to take the string from the client whoever is connecting
            //similarly use the output stream to send the data to the client

            RelativeLayout layout = (RelativeLayout) activity.findViewById(R.id.relativeLayout_Layout);
            TextView text = (TextView) layout.findViewById(R.id.textView_Text);

            text.setText(mmInStream.toString());
        } catch (Exception e) {
            //catch your exception here
        }
    }
}

ここからの SPP クライアントのコード:

/**
* A simple SPP client that connects with an SPP server
*/
public class SampleSPPClient implements DiscoveryListener{

//object used for waiting
private static Object lock=new Object();

//vector containing the devices discovered
private static Vector vecDevices=new Vector();

private static String connectionURL=null;

public static void main(String[] args) throws IOException {

    SampleSPPClient client=new SampleSPPClient();

    //display local device address and name
    LocalDevice localDevice = LocalDevice.getLocalDevice();
    System.out.println("Address: "+localDevice.getBluetoothAddress());
    System.out.println("Name: "+localDevice.getFriendlyName());

    //find devices
    DiscoveryAgent agent = localDevice.getDiscoveryAgent();

    System.out.println("Starting device inquiry...");
    agent.startInquiry(DiscoveryAgent.GIAC, client);

    try {
        synchronized(lock){
            lock.wait();
        }
    }
    catch (InterruptedException e) {
        e.printStackTrace();
    }


    System.out.println("Device Inquiry Completed. ");

    //print all devices in vecDevices
    int deviceCount=vecDevices.size();

    if(deviceCount <= 0){
        System.out.println("No Devices Found .");
        System.exit(0);
    }
    else{
        //print bluetooth device addresses and names in the format [ No. address (name) ]
        System.out.println("Bluetooth Devices: ");
        for (int i = 0; i <deviceCount; i++) {
            RemoteDevice remoteDevice=(RemoteDevice)vecDevices.elementAt(i);
            System.out.println((i+1)+". "+remoteDevice.getBluetoothAddress()+" ("+remoteDevice.getFriendlyName(true)+")");
        }
    }

    System.out.print("Choose Device index: ");
    BufferedReader bReader=new BufferedReader(new InputStreamReader(System.in));

    String chosenIndex=bReader.readLine();
    int index=Integer.parseInt(chosenIndex.trim());

    //check for spp service
    RemoteDevice remoteDevice=(RemoteDevice)vecDevices.elementAt(index-1);
    UUID[] uuidSet = new UUID[1];
    uuidSet[0]=new UUID("446118f08b1e11e29e960800200c9a66", false);

    System.out.println("\nSearching for service...");
    agent.searchServices(null,uuidSet,remoteDevice,client);

    try {
        synchronized(lock){
            lock.wait();
        }
    }
    catch (InterruptedException e) {
        e.printStackTrace();
    }

    if(connectionURL==null){
        System.out.println("Device does not support Simple SPP Service.");
        System.exit(0);
    }

    //connect to the server and send a line of text
    StreamConnection streamConnection=(StreamConnection)Connector.open(connectionURL);

    //send string
    OutputStream outStream=streamConnection.openOutputStream();
    PrintWriter pWriter=new PrintWriter(new OutputStreamWriter(outStream));
    pWriter.write("Test String from SPP Client\r\n");
    pWriter.flush();


    //read response
    InputStream inStream=streamConnection.openInputStream();
    BufferedReader bReader2=new BufferedReader(new InputStreamReader(inStream));
    String lineRead=bReader2.readLine();
    System.out.println(lineRead);


}//main

//methods of DiscoveryListener
public void deviceDiscovered(RemoteDevice btDevice, DeviceClass cod) {
    //add the device to the vector
    if(!vecDevices.contains(btDevice)){
        vecDevices.addElement(btDevice);
    }
}

//implement this method since services are not being discovered
public void servicesDiscovered(int transID, ServiceRecord[] servRecord) {
    if(servRecord!=null && servRecord.length>0){
        connectionURL=servRecord[0].getConnectionURL(0,false);
    }
    synchronized(lock){
        lock.notify();
    }
}

//implement this method since services are not being discovered
public void serviceSearchCompleted(int transID, int respCode) {
    synchronized(lock){
        lock.notify();
    }
}


public void inquiryCompleted(int discType) {
    synchronized(lock){
        lock.notify();
    }

}//end method

}

テストには、最新の Android API を搭載した Galaxy Nexus (GT-I9250) を使用します。

user_CCのおかげで、クライアントとサーバーは例外なく実行されるようになりました。しかし残念なことに、クライアントはサーバーに接続できません (下のスクリーンショットを参照)。これは、connectionURLが設定されていないためです (したがって、デフォルトでここにジャンプしif(connectionURL==null)ます。

クライアントコードを変更して、実際にサーバーに接続できるようにするにはどうすればよいですか? connectionURL次の行に適切なものが必要です。

StreamConnection streamConnection=(StreamConnection)Connector.open(connectionURL)

これまでのところ、どうにかして を取得する必要があることがわかりましたが、悲しいことに、これはhereServiceRecordのサンプル コードにも記載されていません。

ここに画像の説明を入力

4

2 に答える 2

8

RFComm APIS を使用して通信を機能させる必要があります。スレッドであり、サーバーとして機能し、クライアント接続をリッスンするクラスを定義することができました。分かりやすいようにコメントも入れておきました。

    private class AcceptThread extends Thread {
    // The local server socket
    private BluetoothServerSocket mmServerSocket;

    public AcceptThread() {
    }

    public void run() {         
        BluetoothSocket socket = null;

                    BluetoothAdapter mAdapter = BluetoothAdapter.getDefaultAdapter();

        // Listen to the server socket if we're not connected
        while (true) {

            try {
                // Create a new listening server socket
                Log.d(TAG, ".....Initializing RFCOMM SERVER....");

                // MY_UUID is the UUID you want to use for communication
                mmServerSocket = mAdapter.listenUsingRfcommWithServiceRecord(NAME, MY_UUID);                    
                //mmServerSocket = mAdapter.listenUsingInsecureRfcommWithServiceRecord(NAME, MY_UUID);  you can also try using In Secure connection...

                // This is a blocking call and will only return on a
                // successful connection or an exception                    
                socket = mmServerSocket.accept();                   

            } catch (Exception e) {

            }

            try {
                Log.d(TAG, "Closing Server Socket.....";                    
                mmServerSocket.close();



                InputStream tmpIn = null;
                OutputStream tmpOut = null;

                // Get the BluetoothSocket input and output streams

                tmpIn = socket.getInputStream();
                tmpOut = socket.getOutputStream();


                mmInStream = new DataInputStream(tmpIn);
                mmOutStream = new DataOutputStream(tmpOut); 

                // here you can use the Input Stream to take the string from the client whoever is connecting
                //similarly use the output stream to send the data to the client
            } catch (Exception e) {
                //catch your exception here
            }

        }
    }

}

これが役立つことを願っています

別の質問について:

クライアント側 (PC) で javax.bluetooth.UUID を宣言する UUID クラスは javax.bluetooth.UUID から取得する必要があります

   uuidSet2[0] = new UUID("446118f08b1e11e29e960800200c9a66", false);

サーバー側での java.util.UUID の宣言 (Android)

    UUID MY_UUID = UUID.fromString("446118f0-8b1e-11e2-9e96-0800200c9a66");
于 2013-03-11T16:41:39.270 に答える
2

私は Java 開発者ではありませんが、Mono for Android (c#) で同様の問題が発生しました。

SPP の UUID "00001101-0000-1000-8000-00805F9B34FB"
は、Bluetooth SPP アダプターを識別するための既知の UID です。

次のような私のC#コードでは

private static UUID MY_UUID = UUID.FromString("00001101-0000-1000-8000-00805F9B34FB");

Java コードを次のように更新できると思います。

new UUID("00001101-0000-1000-8000-00805F9B34FB", true);

関数が受け入れるパラメータがわからないので、確認する必要があるかもしれません。

私は Android デバイスをクライアントとして使用していましたが、この情報は役に立つかもしれません。
そのため、最初に Java サンプルから翻訳した C# コードをここに含めます。
翻訳して戻すことができるはずです。

btAdapter = BluetoothAdapter.DefaultAdapter;

btAdapter.CancelDiscovery(); //Always call CancelDiscovery before doing anything
remoteDevice = btAdapter.GetRemoteDevice(Settings["deviceaddress"].ToString());

socket = remoteDevice.CreateRfcommSocketToServiceRecord(MY_UUID);
socket.Connect();

基本的に、デフォルトのアダプターを取得し、実行中の検出操作をキャンセルしてから、他のデバイスへのソケットを作成します。あなたの場合、接続する代わりに聞きたいと思うでしょうが、あなたの情報のためだけです。

お役に立てば幸いです。申し訳ありませんが、Java 固有の情報をこれ以上お伝えできませんでした。

「更新:」私が使用しているものと多かれ少なかれ同じ方法に従っている Java の小さなサンプルを見つけました: Android で Bluetooth SPP を接続する際の問題?

于 2013-03-11T16:24:47.280 に答える