当前位置: 移动技术网 > IT编程>移动开发>Android > Android实现的简单蓝牙程序示例

Android实现的简单蓝牙程序示例

2019年07月24日  | 移动技术网IT编程  | 我要评论

本文实例讲述了android实现的简单蓝牙程序。分享给大家供大家参考,具体如下:

我将在这篇文章中介绍了的android蓝牙程序。这个程序就是将实现把手机变做电脑ppt播放的遥控器:用音量加和音量减键来控制ppt页面的切换。

遥控器服务器端

首先,我们需要编写一个遥控器的服务器端(支持蓝牙的电脑)来接收手机端发出的信号。为了实现这个服务器端,我用到了一个叫做bluecove(专门用来为蓝牙服务的!)的java库。

以下是我的remotebluetoothserver类:

public class remotebluetoothserver{
  public static void main(string[] args) {
    thread waitthread = new thread(new waitthread());
    waitthread.start();
  }
}

在主方法中创建了一个线程,用于连接客户端,并处理信号。

public class waitthread implements runnable{
  /** constructor */
  public waitthread() {
  }
  @override
  public void run() {
    waitforconnection();
  }
  /** waiting for connection from devices */
  private void waitforconnection() {
    // retrieve the local bluetooth device object
    localdevice local = null;
    streamconnectionnotifier notifier;
    streamconnection connection = null;
    // setup the server to listen for connection
    try {
      local = localdevice.getlocaldevice();
      local.setdiscoverable(discoveryagent.giac);
      uuid uuid = new uuid(80087355); // "04c6093b-0000-1000-8000-00805f9b34fb"
      string url = "btspp://localhost:" + uuid.tostring() + ";name=remotebluetooth";
      notifier = (streamconnectionnotifier)connector.open(url);
    } catch (exception e) {
      e.printstacktrace();
      return;
    }
        // waiting for connection
    while(true) {
      try {
        system.out.println("waiting for connection...");
            connection = notifier.acceptandopen();
        thread processthread = new thread(new processconnectionthread(connection));
        processthread.start();
      } catch (exception e) {
        e.printstacktrace();
        return;
      }
    }
  }
}

在waitforconnection()中,首先将服务器设为可发现的,并为这个程序创建了uuid(用于同客户端通信);然后就等待来自客户端的连接请求。当它收到一个初始的连接请求时,将创建一个processconnectionthread来处理来自客户端的命令。以下是processconnectionthread的代码:

public class processconnectionthread implements runnable{
  private streamconnection mconnection;
  // constant that indicate command from devices
  private static final int exit_cmd = -1;
  private static final int key_right = 1;
  private static final int key_left = 2;
  public processconnectionthread(streamconnection connection)
  {
    mconnection = connection;
  }
  @override
  public void run() {
    try {
      // prepare to receive data
      inputstream inputstream = mconnection.openinputstream();
      system.out.println("waiting for input");
      while (true) {
        int command = inputstream.read();
        if (command == exit_cmd)
        {
          system.out.println("finish process");
          break;
        }
        processcommand(command);
      }
    } catch (exception e) {
      e.printstacktrace();
    }
  }
  /**
   * process the command from client
   * @param command the command code
   */
  private void processcommand(int command) {
    try {
      robot robot = new robot();
      switch (command) {
        case key_right:
          robot.keypress(keyevent.vk_right);
          system.out.println("right");
          break;
        case key_left:
          robot.keypress(keyevent.vk_left);
          system.out.println("left");
          break;
      }
    } catch (exception e) {
      e.printstacktrace();
    }
  }
}

processconnectionthread类主要用于接收并处理客户端发送的命令。需要处理的命令只有两个:key_right和key_left。我用java.awt.robot来生成电脑端的键盘事件。

以上就是服务器端所需要做的工作。

遥控器客户端

这里的客户端指的其实就是android手机。在开发手机端代码的过程中,我参考了 android dev guide中bluetooth chat这个程序的代码,这个程序在sdk的示例代码中可以找到。

要将客户端连接服务器端,那么必须让手机可以扫描到电脑,devicelistactivity 类的工作就是扫描并连接服务器。bluetoothcommandservice类负责将命令传至服务器端。这两个类与bluetooth chat中的内容相似,只是删除了bluetooth chat中的bluetoothcommandservice中的acceptthread ,因为客户端不需要接受连接请求。connectthread用于初始化与服务器的连接,connectedthread 用于发送命令。

remotebluetooth 是客户端的主activity,其中主要代码如下:

protected void onstart() {
  super.onstart();
  // if bt is not on, request that it be enabled.
    // setupcommand() will then be called during onactivityresult
  if (!mbluetoothadapter.isenabled()) {
    intent enableintent = new intent(bluetoothadapter.action_request_enable);
    startactivityforresult(enableintent, request_enable_bt);
  }
  // otherwise set up the command service
  else {
    if (mcommandservice==null)
      setupcommand();
  }
}
private void setupcommand() {
  // initialize the bluetoothchatservice to perform bluetooth connections
    mcommandservice = new bluetoothcommandservice(this, mhandler);
}

onstart()用于检查手机上的蓝牙是否已经打开,如果没有打开则创建一个intent来打开蓝牙。setupcommand()用于在按下音量加或音量减键时向服务器发送命令。其中用到了onkeydown事件:

public boolean onkeydown(int keycode, keyevent event) {
  if (keycode == keyevent.keycode_volume_up) {
    mcommandservice.write(bluetoothcommandservice.vol_up);
    return true;
  }
  else if (keycode == keyevent.keycode_volume_down){
    mcommandservice.write(bluetoothcommandservice.vol_down);
    return true;
  }
  return super.onkeydown(keycode, event);
}

此外,还需要在androidmanifest.xml加入打开蓝牙的权限的代码。

<uses-permission android:name="android.permission.bluetooth_admin" />
  <uses-permission android:name="android.permission.bluetooth" />

以上就是客户端的代码。

将两个程序分别在电脑和手机上安装后,即可实现用手机当作一个ppt遥控器了!

ps:关于androidmanifest.xml详细内容可参考本站在线工具:

android manifest功能与权限描述大全:

更多关于android相关内容感兴趣的读者可查看本站专题:《android开发入门与进阶教程》、《android视图view技巧总结》、《android编程之activity操作技巧总结》、《android操作sqlite数据库技巧总结》、《android操作json格式数据技巧总结》、《android数据库操作技巧总结》、《android文件操作技巧汇总》、《android编程开发之sd卡操作方法汇总》、《android资源操作技巧汇总》及《android控件用法总结

希望本文所述对大家android程序设计有所帮助。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网