Android實現的簡單藍芽程式樣本_Android

來源:互聯網
上載者:User

本文執行個體講述了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功能與許可權描述大全:

http://tools.jb51.net/table/AndroidManifest

更多關於Android相關內容感興趣的讀者可查看本站專題:《Android開發入門與進階教程》、《Android視圖View技巧總結》、《Android編程之activity操作技巧總結》、《Android操作SQLite資料庫技巧總結》、《Android操作json格式資料技巧總結》、《Android資料庫操作技巧總結》、《Android檔案操作技巧匯總》、《Android編程開發之SD卡操作方法匯總》、《Android資源操作技巧匯總》及《Android控制項用法總結》

希望本文所述對大家Android程式設計有所協助。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.