通过蓝牙从Java服务器发送短信到Android客户端 [英] Send text through Bluetooth from Java Server to Android Client

查看:161
本文介绍了通过蓝牙从Java服务器发送短信到Android客户端的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先...不要重定向我到蓝牙聊天,我已经完全读它。

我有一个Android客户端它恰当stablishes的连接与服务器,什么是最让我可以在我的电脑文本发送到服务器,并正确地表现出来,但我不能做相反的操作,从发送一个简单的字符串服务器到客户端,并显示在我的Andr​​oid应用程序。

我不想要实现一个聊天只是为了显示BT通信Java服务器和Android客户端之间是如何工作的。

为了方便:

我把在服务器类的startserver的()方法的最后文本。

我试着在的onPause的开始从服务器读取的文本()。

**

[解决]解决方案在

**。

在code是如下:

Android的BT客户端:

  / * ...这里库... * /
  公共类ConnectTest延伸活动{
  TextView中出;
  私有静态最终诠释REQUEST_ENABLE_BT = 1;
  私人BluetoothAdapter btAdapter = NULL;
  私有的BluetoothSocket btSocket = NULL;
  私人的OutputStream outStream = NULL;

  //众所周知SPP UUID
  私有静态最后UUID MY_UUID =
      UUID.fromString(00001101-0000-1000-8000-00805F9B34FB);

  //将您的服务器的MAC地址
  私有静态字符串地址=00:10:60:AA:B9:B2;

  / **第一次创建活动时调用。 * /
  公共无效的onCreate(包savedInstanceState){
    super.onCreate(savedInstanceState);
    的setContentView(R.layout.main);

    OUT =(TextView中)findViewById(R.id.out);

    out.append(\ñ......在的onCreate()...);

    btAdapter = BluetoothAdapter.getDefaultAdapter();
    CheckBTState();
  }

  公共无效的OnStart(){
    super.onStart();
    out.append(\ñ......在ONSTART()...);
  }

  公共无效onResume(){
    super.onResume();

    out.append(\ñ......在onResume ...... \ñ正在试图客户端连接......);

    //设置一个指针到远程节点使用它的地址。
    BluetoothDevice类设备= btAdapter.getRemoteDevice(地址);

    需要//两件事情来建立连接:
    // MAC地址,这是我们得到了上面。
    //服务ID或UUID。在这种情况下,我们使用的是
    // UUID为SPP。
    尝试 {
      btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
    }赶上(IOException异常E){
      AlertBox(致命错误,在onResume()和插座创建失败:+ e.getMessage()+。);
    }

    //发现是资源密集型的。请确保它不会对
    //当您尝试连接并传递你的信息。
    btAdapter.cancelDiscovery();

    //建立连接。这将阻止,直到它连接。
    尝试 {
      btSocket.connect();
      out.append(\ñ......连接建立和数据链接打开...);
    }赶上(IOException异常E){
      尝试 {
        btSocket.close();
      }赶上(IOException异常E2){
        AlertBox(致命错误,在onResume()和无法连接的故障期间关闭套接字+ e2.getMessage()+。);
      }
    }

    //创建一个数据流,所以我们可以跟服务器。
    out.append(\ñ......发送消息到服务器...);
    字符串消息=你好,从Android的\ N的;
    out.append(\ñ\ñ......,我们将发送到服务器的信息是:+消息);

    尝试 {
      outStream = btSocket.getOutputStream();
    }赶上(IOException异常E){
      AlertBox(致命错误,在onResume()和输出流创建失败:+ e.getMessage()+。);
    }

    byte []的msgBuffer = message.getBytes();
    尝试 {
      outStream.write(msgBuffer);
    }赶上(IOException异常E){
      弦乐味精=在onResume()和异常写入过程中出现:+ e.getMessage();
      如果(address.equals(00:00:00:00:00:00))
        \ñ\ nUpdate从00服务器地址:00:00:00:00:00就在java code线37的正确地址味精=味精+;
      味精=味精+\ñ\ n检查最高人民检察院UUID:+ MY_UUID.toString()+存在于服务器\ñ\ñ。

      AlertBox(致命错误,味精);
    }
  }

  公共无效的onPause(){
    super.onPause();

    //out.append("\n...Hello\n);
    为InputStream inStream中;
    尝试 {
        inStream中= btSocket.getInputStream();
        的BufferedReader面包屑=新的BufferedReader(新的InputStreamReader(inStream中));
        串lineRead = bReader.readLine();
        out.append(\ñ......+ lineRead +\ N);

    }赶上(IOException异常E){
        // TODO自动生成的catch块
        e.printStackTrace();
    }

    out.append(\ñ......在的onPause()...);



    如果(outStream!= NULL){
      尝试 {
        outStream.flush();
      }赶上(IOException异常E){
        AlertBox(致命错误,在的onPause(),并未能刷新输出流:+ e.getMessage()+。);
      }
    }

    尝试     {
      btSocket.close();
    }赶上(IOException异常E2){
      AlertBox(致命错误,在的onPause(),并没有关闭套接字。+ e2.getMessage()+。);
    }
  }

  公共无效的onStop(){
    super.onStop();
    out.append(\ñ......在的onStop()...);
  }

  公共无效的onDestroy(){
    super.onDestroy();
    out.append(\ñ......在的onDestroy()...);
  }

  私人无效CheckBTState(){
    //检查支持蓝牙,然后检查,以确保它已开启

    //仿真器不支持蓝牙和将返回null
    如果(btAdapter == NULL){
      AlertBox(致命错误,蓝牙不支持败。);
    } 其他 {
      如果(btAdapter.isEnabled()){
        out.append(\ñ...蓝牙启用......);
      } 其他 {
        //提示用户打开蓝牙
        意图enableBtIntent =新的意图(btAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(enableBtIntent,REQUEST_ENABLE_BT);
      }
    }
  }

  公共无效AlertBox(标题字符串,字符串消息){
    新AlertDialog.Builder(本)
    .setTitle(标题)
    .setMessage(信息+preSS确定退出。)
    .setPositiveButton(OK,新OnClickListener(){
        公共无效的onClick(DialogInterface为arg0,INT ARG1){
          完();
        }
    })。显示();
  }
}
 

和Java BT服务器:

 进口java.io.BufferedReader中;
进口java.io.BufferedWriter中;
进口java.io.IOException异常;
进口的java.io.InputStream;
进口java.io.InputStreamReader中;
进口java.io.OutputStream中;
进口java.io.OutputStreamWriter中;
进口的java.io.PrintWriter;

进口javax.bluetooth *。
进口javax.microedition.io *。

/ **
*实现,它接受了单线的SPP服务器类
*从一个SPP客户端消息,并发送响应于客户端的一单行。
* /
公共类SimpleSPPServer {

    //启动服务器
    私人无效startserver的()抛出IOException异常{

        //创建一个UUID为SPP
        UUID UUID =新的UUID(1101,真正的);
        //创建servicve网址
        字符串的connectionString =btspp://本地主机:+ UUID +;名称=采样SPP服务器;

        //打开服务器的URL
        StreamConnectionNotifier streamConnNotifier =(StreamConnectionNotifier)Connector.open(的connectionString);

        //等待客户端的连接
        的System.out.println(\ n服务器已开始等待客户端进行连接......。);
        的StreamConnection连接= streamConnNotifier.acceptAndOpen();

        远端设备开发= RemoteDevice.getRemoteDevice(连接);
        的System.out.println(远程设备地址:+ dev.getBluetoothAddress());
        的System.out.println(远程设备名称:+ dev.getFriendlyName(真));

        //从SPP客户端读取的字符串
        的InputStream inStream中= connection.openInputStream();
        的BufferedReader面包屑=新的BufferedReader(新的InputStreamReader(inStream中));
        串lineRead = bReader.readLine();
        的System.out.println(lineRead);

        //发送响应属客户端
        OutputStream的outStream = connection.openOutputStream();
        BufferedWriter将bWriter =新的BufferedWriter(新OutputStreamWriter(outStream));
        bWriter.write(响应字符串从SPP服务器\ r \ N);

        / * PrintWriter的pWriter =的新PrintWriter(新OutputStreamWriter(outStream));
        pWriter.write(响应字符串从SPP服务器\ r \ N);
        pWriter.flush();
        pWriter.close(); * /

        streamConnNotifier.close();

    }


    公共静态无效的主要(字串[] args)抛出IOException异常{

        //显示本地设备地址和名称
        LocalDevice的LocalDevice的= LocalDevice.getLocalDevice();
        的System.out.println(地址:+ localDevice.getBluetoothAddress());
        的System.out.println(姓名:+ localDevice.getFriendlyName());

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

    }
}
 

解决方案的: 这是在服务器端只是一个小的变化。 我不知道为什么,但不是使用BufferedWrite在插座写,我们需要使用PrinterWriter这样做。我补充一点,这块code修改:

BT服务器:

  ....
    //从SPP客户端读取的字符串
    的InputStream inStream中= connection.openInputStream();
    的BufferedReader面包屑=新的BufferedReader(新的InputStreamReader(inStream中));
    串lineRead = bReader.readLine();
    的System.out.println(lineRead);

    //发送响应属客户端
    OutputStream的outStream = connection.openOutputStream();
    PrintWriter的pWriter =的新PrintWriter(新OutputStreamWriter(outStream));
    pWriter.write(响应字符串从SPP服务器\ r \ N);
    pWriter.flush();

    pWriter.close();

    streamConnNotifier.close();
    ...
 

解决方案

它看起来像你的BufferedWriter缓存没有被刷新,数据被简单地保留在缓存而不被发送。呼叫 bWriter.flush()后,你的 bWriter.write()应该解决的问题,并导致数据被刷新到输出流。您也可以考虑更改您的code遵循这样的:

 的PrintWriter pWriter =的新PrintWriter(新的BufferedWriter(新OutputStreamWriter(outStream)));
 

这将导致的PrintWriter输出进行缓冲,而不是被立即写入到输出流,这可能是效率低下。

有关您的目的虽然省略的BufferedWriter应罚款,因为你很可能要立即刷新到输出流(其中的PrintWriter呢)。

First of all... don't redirect me to Bluetooth Chat and I have fully read it.

I have an Android Client which stablishes the connection properly with the server, and what's most I can send text to the server in my pc and show it correctly, but I can't do the opposite action, send a simple string from the server to the client and show it in my android app.

I don't want to implement a chat is just to show how BT communication works between a Java Server and Android Client.

To make it easy:

I send the text at the end of the startServer() method in the server class.

I try to read the text from the server at the beginning of onPause().

**

[Solved] Solution Below

**.

The code is as follows:

Android BT Client:

/*...libraries here...*/
  public class ConnectTest extends Activity {
  TextView out;
  private static final int REQUEST_ENABLE_BT = 1;
  private BluetoothAdapter btAdapter = null;
  private BluetoothSocket btSocket = null;
  private OutputStream outStream = null;

  // Well known SPP UUID
  private static final UUID MY_UUID =
      UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");

  // Insert your server's MAC address
  private static String address = "00:10:60:AA:B9:B2";

  /** Called when the activity is first created. */
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    out = (TextView) findViewById(R.id.out);

    out.append("\n...In onCreate()...");

    btAdapter = BluetoothAdapter.getDefaultAdapter();
    CheckBTState();
  }

  public void onStart() {
    super.onStart();
    out.append("\n...In onStart()...");
  }

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

    out.append("\n...In onResume...\n...Attempting client connect...");

    // Set up a pointer to the remote node using it's address.
    BluetoothDevice device = btAdapter.getRemoteDevice(address);

    // Two things are needed to make a connection:
    //   A MAC address, which we got above.
    //   A Service ID or UUID.  In this case we are using the
    //     UUID for SPP.
    try {
      btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
    } catch (IOException e) {
      AlertBox("Fatal Error", "In onResume() and socket create failed: " + e.getMessage() + ".");
    }

    // Discovery is resource intensive.  Make sure it isn't going on
    // when you attempt to connect and pass your message.
    btAdapter.cancelDiscovery();

    // Establish the connection.  This will block until it connects.
    try {
      btSocket.connect();
      out.append("\n...Connection established and data link opened...");
    } catch (IOException e) {
      try {
        btSocket.close();
      } catch (IOException e2) {
        AlertBox("Fatal Error", "In onResume() and unable to close socket during connection failure" + e2.getMessage() + ".");
      }
    }

    // Create a data stream so we can talk to server.
    out.append("\n...Sending message to server...");
    String message = "Hello from Android.\n";
    out.append("\n\n...The message that we will send to the server is: "+message);

    try {
      outStream = btSocket.getOutputStream();
    } catch (IOException e) {
      AlertBox("Fatal Error", "In onResume() and output stream creation failed:" + e.getMessage() + ".");
    }

    byte[] msgBuffer = message.getBytes();
    try {
      outStream.write(msgBuffer);
    } catch (IOException e) {
      String msg = "In onResume() and an exception occurred during write: " + e.getMessage();
      if (address.equals("00:00:00:00:00:00")) 
        msg = msg + ".\n\nUpdate your server address from 00:00:00:00:00:00 to the correct address on line 37 in the java code";
      msg = msg +  ".\n\nCheck that the SPP UUID: " + MY_UUID.toString() + " exists on server.\n\n";

      AlertBox("Fatal Error", msg);       
    }
  }

  public void onPause() {
    super.onPause();

    //out.append("\n...Hello\n");
    InputStream inStream;
    try {
        inStream = btSocket.getInputStream();
        BufferedReader bReader=new BufferedReader(new InputStreamReader(inStream));
        String lineRead=bReader.readLine();
        out.append("\n..."+lineRead+"\n");

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

    out.append("\n...In onPause()...");



    if (outStream != null) {
      try {
        outStream.flush();
      } catch (IOException e) {
        AlertBox("Fatal Error", "In onPause() and failed to flush output stream: " + e.getMessage() + ".");
      }
    }

    try     {
      btSocket.close();
    } catch (IOException e2) {
      AlertBox("Fatal Error", "In onPause() and failed to close socket." + e2.getMessage() + ".");
    }
  }

  public void onStop() {
    super.onStop();
    out.append("\n...In onStop()...");
  }

  public void onDestroy() {
    super.onDestroy();
    out.append("\n...In onDestroy()...");
  }

  private void CheckBTState() {
    // Check for Bluetooth support and then check to make sure it is turned on

    // Emulator doesn't support Bluetooth and will return null
    if(btAdapter==null) { 
      AlertBox("Fatal Error", "Bluetooth Not supported. Aborting.");
    } else {
      if (btAdapter.isEnabled()) {
        out.append("\n...Bluetooth is enabled...");
      } else {
        //Prompt user to turn on Bluetooth
        Intent enableBtIntent = new Intent(btAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
      }
    }
  }

  public void AlertBox( String title, String message ){
    new AlertDialog.Builder(this)
    .setTitle( title )
    .setMessage( message + " Press OK to exit." )
    .setPositiveButton("OK", new OnClickListener() {
        public void onClick(DialogInterface arg0, int arg1) {
          finish();
        }
    }).show();
  }
}

and the Java BT Server:

    import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;

import javax.bluetooth.*;
import javax.microedition.io.*;

/**
* Class that implements an SPP Server which accepts single line of
* message from an SPP client and sends a single line of response to the client.
*/
public class SimpleSPPServer {

    //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=Sample SPP Server";

        //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);

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

        /*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();

    }
}

Solution: It's just a small change in the server side. I don't know why but instead of using BufferedWrite to write in the socket, we need to use PrinterWriter to do so. I add that piece of code modified:

BT Server:

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

    //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();
    ...

解决方案

It looks like your BufferedWriter cache was not being flushed, the data was simply remaining in the buffer without being sent. Calling bWriter.flush() after your bWriter.write() should fix the issue and cause the data to be flushed to the output stream. You can also consider changing your code to follow this:

PrintWriter pWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outStream)));

This will cause the PrintWriter output to be buffered, instead of being written immediately to the output stream, which can be inefficient.

For your purposes though, omitting the BufferedWriter should be fine, as you will most likely want an immediate flush to the output stream (which PrintWriter does).

这篇关于通过蓝牙从Java服务器发送短信到Android客户端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆