java - Android 和 java 蓝牙客户端服务器应用程序

标签 java android bluetooth server client

我有一个安卓应用。我想在我的客户端应用程序中每次触摸按钮时向 Java 服务器发送一个字符串。我能够连接到服务器。

但问题是当我触摸按钮时,没有字符串发送到服务器。无论我触摸按钮多少次,字符串都没有发送,但是当我退出智能手机中的应用程序时突然,这意味着当我破坏 Activity 时,所有字符串都会同时传输到服务器。

如果我触摸按钮 100 次,只有当我销毁 Activity 时,才会将 100 个相同的字符串传输到服务器。我希望在触摸按钮时将字符串传输到服务器。

请帮我解决这个问题。我是新手。我的代码如下:

public class Joystick extends Activity {
BluetoothAdapter ba=BluetoothAdapter.getDefaultAdapter();
//local bluetooth adapter object created
BluetoothDevice bd;                                                                 //GLOBAL DECLARATION BLOCK
BluetoothSocket bs;
OutputStream os;
InputStream in;
Button up;
private static final UUID MY_UUID =UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.joystick);
    up= (Button) findViewById(R.id.up);

    if(ba.isEnabled()==false)                                                       //BLUETOOTH ADAPTER ENABLED IF WAS DISABLED
        ba.enable();
    final String address = getIntent().getStringExtra("address").trim();
    setResult(100, new Intent());
    bd=ba.getRemoteDevice(address);
    BluetoothConnect.start();


}
@Override
protected void onResume(){
    super.onResume();
    up.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    try {
                        os = bs.getOutputStream();
                        String message = "up";
                        byte[] msgBuffer = message.getBytes();
                        os.write(msgBuffer);



                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    break;

                case MotionEvent.ACTION_UP:
                    try {
                        os.flush();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    break;



            }
            return true;
        }
    });


}
Thread BluetoothConnect = new Thread(){
    public void run(){
        try {
            bs=bd.createRfcommSocketToServiceRecord(MY_UUID);
            bs.connect();


        } catch (IOException e) {
            try {
                bs.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            e.printStackTrace();
        }

    }

};
protected void onStop(){
    super.onStop();

    try {
        os.close();
        bs.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
@Override
protected void onPause() {
    super.onPause();
    if (os != null) {
        try {
            os.flush();
        } catch (IOException e) {

        }
}
}}

服务器代码是:

public class SimpleSPPServer {
private static Robot robot;
//start server
private void startServer() throws IOException{

    //Create a UUID for SPP
    UUID uuid = new UUID("1101", true);
    //Create the servicve url
    String connectionString = "btspp://localhost:" + uuid +";name=SampleSPPServer";

    //open server url
    StreamConnectionNotifier streamConnNotifier = (StreamConnectionNotifier)Connector.open( connectionString );

    //Wait for client connection
    System.out.println("\nServer Started. Waiting for clients to connect...");
    StreamConnection connection=streamConnNotifier.acceptAndOpen();

    RemoteDevice dev = RemoteDevice.getRemoteDevice(connection);
    System.out.println("Remote device address: "+dev.getBluetoothAddress());
    System.out.println("Remote device name: "+dev.getFriendlyName(true));

    //read string from spp client
    InputStream inStream=connection.openInputStream();
    BufferedReader bReader=new BufferedReader(new InputStreamReader(inStream));
    String lineRead=bReader.readLine();
    System.out.println(lineRead);
    try{
        robot=new Robot();

    if(lineRead.equalsIgnoreCase("up")){                        
robot.keyPress(KeyEvent.VK_UP);
robot.keyRelease(KeyEvent.VK_UP);
    }       }
    catch(AWTException e){
        System.out.println("exception while creating robot instance");
    }

    //send response to spp client
    OutputStream outStream=connection.openOutputStream();
    PrintWriter pWriter=new PrintWriter(new OutputStreamWriter(outStream));
    pWriter.write("Response String from SPP Server\r\n");
    pWriter.flush();

    pWriter.close();
    streamConnNotifier.close();

}


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

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

    SimpleSPPServer sampleSPPServer=new SimpleSPPServer();
    sampleSPPServer.startServer();

}
}

最佳答案

问题已解决..只需在要传输的字符串末尾添加“\n”即可。

关于java - Android 和 java 蓝牙客户端服务器应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37363098/

相关文章:

java - 使用 INNER JOIN 查询

java - JPA不保存带有@Transactional注释的选择结果

java - 字符串和内存管理

android - 解析本地数据存储和 ParseQueryAdapter 导致启用固定时不允许方法

java - 无法从 BLE nordic thingy :52 检索 RSSI 值

java - 有没有办法在连接到 Active MQ 队列时让 Spring JMS 监听器有初始延迟?

java - ArrayList Adapter (for ListView) 只显示第一个添加的项目

android - 从一个 Activity 中获取文本并将其设置到另一个 Activity 中

android - Android蓝牙低功耗回调(LeScanCallBack)在单独的线程上?

c - 结合使用 Arduino Motor Shield 和 Bluetooth Shield