android 安卓蓝牙客户端服务器连接

pwuypxnk  于 2023-04-04  发布在  Android
关注(0)|答案(2)|浏览(184)

我想创建一个简单的Android蓝牙客户端-服务器程序

服务器编码:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    tv1=(TextView)findViewById(R.id.textView1);
    tv2=(TextView)findViewById(R.id.textView2);
    mBluetoothAdapter=BluetoothAdapter.getDefaultAdapter();
    try {
        mBluetoothServerSocket=mBluetoothAdapter.listenUsingRfcommWithServiceRecord(name,uUID);
        mBluetoothAdapter.cancelDiscovery();
        mBluetoothSocket=mBluetoothServerSocket.accept();
        mInputStream=mBluetoothSocket.getInputStream();
        //if(mInputStream.available()>0){
            mBufferedReader=new BufferedReader(new InputStreamReader(mInputStream));
            data = mBufferedReader.readLine();
            tv1.setText(data);
        //} 
            if(mInputStream.available()>0){
            data=mBufferedReader.readLine();
            tv2.setText(data);
            x++;
        }

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

客户编码:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    lb=(Button)findViewById(R.id.button1);
    btAdapter = BluetoothAdapter.getDefaultAdapter();

      BluetoothDevice device = btAdapter.getRemoteDevice(addressHTC);
      try {
        btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
        btAdapter.cancelDiscovery();
        btSocket.connect();
        String message = "Hello.............. from....... Android......\n";
        outStream = btSocket.getOutputStream();
        byte[] msgBuffer = message.getBytes();
        outStream.write(msgBuffer);
      }
    catch(IOException e){
        e.printStackTrace();    
    }
      lb.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            String m1="msg 2";
            byte[] msgBuffer = m1.getBytes();
            try {
                outStream.write(msgBuffer);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
    });
}

这个应用程序工作在一个侧面模式,只是发送消息到服务器和显示收到的缓冲区,但我需要发送回一些消息从服务器到客户端不断。
怎么做呢?
如果你有什么想法,请分享。

b09cbbtk

b09cbbtk1#

这对我连续阅读很有用。试试吧。

try {
            BufferedReader Reader = new BufferedReader(
                    new InputStreamReader(mmSocket.getInputStream()));

            while(true)
            {                   
                String receivedMsg;
                while((receivedMsg = Reader.readLine()) != null)
                {
                     // what you do with your message 
                }

            }
        } catch (Exception ex) {
            System.out.println(ex);
        }
js81xvg6

js81xvg62#

你应该有一个不同的线程用于监听,它将发送消息到Activity,这个线程也可以是发送消息的线程。这样你的UI就不会卡住,你可以连续接收消息。这样的线程的一个例子:

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import android.app.Activity;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.util.Log;

public class MessageManager extends Thread {

private static final String TAG = "MessageListener thread";
private BluetoothSocket btConnectedSocket;
private InputStream inStream;
private OutputStream outStream;
private Activity parent;
private boolean run = true;

public MessageManager(BluetoothSocket btConnectedSocket, Activity parent) throws IOException {
    this.btConnectedSocket = btConnectedSocket;
    this.parent = parent;
    inStream =  btConnectedSocket.getInputStream();
    outStream = btConnectedSocket.getOutputStream();        
}

/* this method will listen continuously to messages received through the BT socket until you call cancel
public void run() {
    byte[] buffer = new byte[1024];
    int bytes; 

    while (run) {
        try {
            bytes = inStream.read(buffer);
        }
        catch(IOException ex) {
            Log.e(TAG, "error while reading from bt socket");

        }
        parent.doStuffWithTheMessage(buffer); // pay attention: its in bytes. u need to convert it to a string
    }
}

/* Call this from the main activity to send data to the remote device */
public void write(byte[] bytes) throws IOException{
        outStream.write(bytes);
}

/* Call this from the main activity to shutdown the connection */
public void cancel() {
    run = false;
    try {
        btConnectedSocket.close();
    } catch (IOException e) { }

}

}

相关问题