編輯:關於 Android 程式設計
前兩篇都在討論手機之間的連接、連接方法以及主動配對連接,都是手機對手機的操作,做起來還算順利。但最終目標其實是與單片機的藍牙模組進行通訊。
下面是到目前為止嘗試過的與單片機通訊的方法。雖然還沒有成功,但從思路上講是沒有問題的。最大的難點在於:與單片機配對時,單片機藍牙模組的 PIN 配對碼是寫死的,固定為 1234;而手機這邊的連接配對碼是自動生成的,這種方式在手機對手機配對時極為方便,但在這裡與單片機連接時反而成了最大的障礙——因為手機自動生成、而且每次都不一樣,所以無法與單片機藍牙模組固定的 1234 相匹配,也就無法完成配對。下面僅介紹到目前為止我們的大致思路,由於涉及具體專案,就不貼完整程式碼了。
如果關於上述問題哪位朋友有思路,或者做過類似專案,還請不吝指點。
首先,如何開啟藍牙裝置並設定可見時間:
private void search() { BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter(); if (!adapter.isEnabled()) { adapter.enable(); } Intent enable = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE); enable.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 3600); //3600為藍牙設備可見時間 startActivity(enable); Intent searchIntent = new Intent(this, ComminuteActivity.class); startActivity(searchIntent); }
接著正式進入與藍牙模組通訊的部分:
public class ComminuteActivity extends Activity { private BluetoothReceiver receiver; private BluetoothAdapter bluetoothAdapter; private List devices; private List deviceList; private Bluetooth client; private final String lockName = "YESYOU"; private String message = "000001"; private ListView listView; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.search_layout); listView = (ListView) this.findViewById(R.id.list); deviceList = new ArrayList(); devices = new ArrayList(); bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); bluetoothAdapter.startDiscovery(); IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND); receiver = new BluetoothReceiver(); registerReceiver(receiver, filter); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView> parent, View view, int position, long id) { setContentView(R.layout.connect_layout); BluetoothDevice device = deviceList.get(position); client = new Bluetooth(device, handler); try { client.connect(message); } catch (Exception e) { Log.e("TAG", e.toString()); } } }); } @Override protected void onDestroy() { unregisterReceiver(receiver); super.onDestroy(); } private final Handler handler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case Bluetooth.CONNECT_FAILED: Toast.makeText(ComminuteActivity.this, "連接失敗", Toast.LENGTH_LONG).show(); try { client.connect(message); } catch (Exception e) { Log.e("TAG", e.toString()); } break; case Bluetooth.CONNECT_SUCCESS: Toast.makeText(ComminuteActivity.this, "連接成功", Toast.LENGTH_LONG).show(); break; case Bluetooth.READ_FAILED: Toast.makeText(ComminuteActivity.this, "讀取失敗", Toast.LENGTH_LONG).show(); break; case Bluetooth.WRITE_FAILED: Toast.makeText(ComminuteActivity.this, "寫入失敗", Toast.LENGTH_LONG).show(); break; case Bluetooth.DATA: Toast.makeText(ComminuteActivity.this, msg.arg1 + "", Toast.LENGTH_LONG).show(); break; } } }; private class BluetoothReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (BluetoothDevice.ACTION_FOUND.equals(action)) { BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); if (isLock(device)) { devices.add(device.getName()); } deviceList.add(device); } showDevices(); } } private boolean isLock(BluetoothDevice device) { boolean isLockName = (device.getName()).equals(lockName); boolean isSingleDevice = devices.indexOf(device.getName()) == -1; return isLockName && isSingleDevice; } private void showDevices() { ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, devices); listView.setAdapter(adapter); } }
這裡要特別提一下 startDiscovery() 方法及其行為:它是一個非同步方法,會去搜尋其他藍牙裝置,持續時間約 12 秒。搜尋過程實際上是在 System Service 中進行的,我們可以透過 cancelDiscovery() 方法提前停止搜尋。在系統搜尋藍牙裝置的過程中,可能會發送以下三個廣播:ACTION_DISCOVERY_START(開始搜尋)、ACTION_DISCOVERY_FINISHED(搜尋結束)和 ACTION_FOUND(找到裝置)。
其中 ACTION_FOUND 才是我們真正需要的,這個 Intent 包含兩個 extra 欄位:EXTRA_DEVICE 和 EXTRA_CLASS,分別對應 BluetoothDevice 和 BluetoothClass。EXTRA_DEVICE 中的 BluetoothDevice 就是我們搜尋到的裝置物件,從中可以获得裝置的名稱和位址;而 EXTRA_CLASS 中的 BluetoothClass 則是搜尋到裝置的類型,比如是手機、耳機還是其他裝置。
基於這一點,我目前在想:是否能透過判斷搜尋到的裝置類型,來識別單片機藍牙模組與手機藍牙的不同,進而採取不一樣的配對方式,避免自動生成配對碼。是否可行,待會兒可以試一試。
搜尋到目標裝置後,接下來就要對它進行連接與通訊。
public void connect(final String message) { Thread thread = new Thread(new Runnable() { public void run() { BluetoothSocket tmp = null; Method method; try { method = device.getClass().getMethod("createRfcommSocket", new Class[]{int.class}); tmp = (BluetoothSocket) method.invoke(device, 1); } catch (Exception e) { setState(CONNECT_FAILED); Log.e("TAG", e.toString()); } socket = tmp; try { socket.connect(); isConnect = true; } catch (Exception e) { setState(CONNECT_FAILED); Log.e("TAG", e.toString()); } if (isConnect) { try { OutputStream outStream = socket.getOutputStream(); outStream.write(getHexBytes(message)); } catch (IOException e) { setState(WRITE_FAILED); Log.e("TAG", e.toString()); } try { InputStream inputStream = socket.getInputStream(); int data; while (true) { try { data = inputStream.read(); Message msg = handler.obtainMessage(); msg.what = DATA; msg.arg1 = data; handler.sendMessage(msg); } catch (IOException e) { setState(READ_FAILED); Log.e("TAG", e.toString()); break; } } } catch (IOException e) { setState(WRITE_FAILED); Log.e("TAG", e.toString()); } } if (socket != null) { try { socket.close(); } catch (IOException e) { Log.e("TAG", e.toString()); } } } });
這裡包含了寫入與讀取,用法和基本的 Socket 一樣,只不過寫入時需要把字串轉換為 16 進位:
private byte[] getHexBytes(String message) { int len = message.length() / 2; char[] chars = message.toCharArray(); String[] hexStr = new String[len]; byte[] bytes = new byte[len]; for (int i = 0, j = 0; j < len; i += 2, j++) { hexStr[j] = "" + chars[i] + chars[i + 1]; bytes[j] = (byte) Integer.parseInt(hexStr[j], 16); } return bytes; }
連接裝置之前需要 UUID,也就是用來配對的 Universally Unique Identifier,它是一個 128 位元的字串 ID,用於唯一標識。網路上的例子(包括 Google 官方範例)所提供的通用 UUID "00001101-0000-1000-8000-00805F9B34FB" 我都試過了,配對時仍然會自動生成配對碼,無法正常與單片機的藍牙模組連接。於是我就利用反射的原理,讓裝置自己提供 UUID 來嘗試。寫到這裡,我甚至開始懷疑自己對 UUID 的理解是否正確了。
在 Google 提供的範例中,可以看到其程式員水準很高,一些良好的編碼習慣值得我們學習。比如在 try...catch 中才定義的變數,我們應該在 try...catch 之前先宣告一個臨時變數,再在 try...catch 之後賦值給真正要使用的變數。這樣做的好處是:如果直接使用真正的變數,一旦出現異常,該變數的使用就會出問題,而且很難排查;而用臨時變數,我們就可以透過檢查變數的值來判斷是否是賦值環節出了錯。
用原生 GridView 做一個九宮格功能頁
需求背景 新專案有個頁面要做成九宮格:每個 Item 上方一張圖片、下方一行文字說明,點擊後跳到對應的功能頁。與其去找第三方庫,不如直接用 Android 原生的 Gri
Android Touch 事件分發機制學習筆記
Android 中的事件主要分為按鍵事件與觸摸事件。Touch 事件由一個 ACTION_DOWN、n 個 ACTION_MOVE 與一個 ACTION_UP 組成,最終
Android 開發效率補給:SDK 更新、Eclipse 掛載源碼與離線文件
自從 Google 被牆之後,Android 開發者有段時間過得挺辛苦:官網打不開、SDK 更新不了、源碼抓不下來。身為一個有追求的開發者,滿足於只會用 SDK 顯然不夠
Android Gallery 搭配 ImageSwitcher:打造帶淡入淡出的圖片瀏覽效果
Gallery 提供橫向滾動的縮圖列表,ImageSwitcher 則負責在其上方展示大圖並支援切換動畫。兩者搭配,就能做出經典的圖片瀏覽器效果。 一、布局 activ