[Bluetooth] Bluetooth serial port 發送資料
本帖最後由 frank 於 2011-5-18 19:02 編輯
本例子作為客戶端(Client)利用主機(Server)的藍牙設備名稱作條件,發送資料到主機.
AndroidManifest.xml
- <?xml version="1.0" encoding="utf-8"?>
- <manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="com.openplatform.bluetooth_test"
- android:versionCode="1"
- android:versionName="1.0">
- //新增這句令這程式有權限進行藍牙裝置的設定和搜尋裝置
- <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" /> //新增這句令這程式有權限進行藍牙連接和通信
- <uses-permission android:name="android.permission.BLUETOOTH" />
- <application android:debuggable="true" android:icon="@drawable/icon" android:label="@string/app_name">
- <activity android:name=".Bluetooth_Test"
- android:label="@string/app_name">
- <intent-filter>
- <action android:name="android.intent.action.MAIN" />
- <category android:name="android.intent.category.LAUNCHER" />
- </intent-filter>
- </activity>
- </application>
- </manifest>
複製代碼
Bluetooth_Test.java
- import android.app.Activity;
- import android.bluetooth.BluetoothAdapter;
- import android.bluetooth.BluetoothDevice;
- import android.bluetooth.BluetoothSocket;
- import android.widget.Toast;
- import android.content.*;
- import android.util.Log;
- public class Bluetooth_Test extends Activity {
-
- private static final String TAG = "Bluetooth_Test";
- private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
- private static String bt_hostname = "openplatform";
- private BluetoothAdapter mBluetoothAdapter = null;
- private BluetoothDevice mBluetoothDevice = null;
- private final int REQUEST_ENABLE_BT = 1;
- private static final boolean D = true; //for debug use
- private static boolean start_discovery = false;
- //Bluetooth thread variable
- private ConnectThread mConnectThread;
- private ConnectedThread mConnectedThread;
- /** Called when the activity is first created. */
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
- if (mBluetoothAdapter == null) {
- // Device does not support Bluetooth
- Toast.makeText(this,
- "此裝置沒有藍牙設備",
- Toast.LENGTH_LONG).show();
- finish();
- return;
- }
- if (!mBluetoothAdapter.isEnabled()) {
- //Enable the bluetooth if this is disabled
- Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
- startActivityForResult(enableBtIntent,REQUEST_ENABLE_BT);
- }
- else {
- //Bluetooth was find start search bluetooth device
- listItems.add("程式已啟動");
- connectLED();
- }
- @Override
- public void onDestroy() {
- super.onDestroy();
-
- if (D) Log.e(TAG, "+++ ON Destory +++");
-
- //stop discovery bluetooth device
- if(start_discovery) {
- mBluetoothAdapter.cancelDiscovery();
- unregisterReceiver(myReceiver);
- }
-
- //cancel the mConnectThread
- if (mConnectThread != null)
- mConnectThread.cancel();
-
- //cancel the mConnectedThread
- if (mConnectedThread != null)
- mConnectedThread.cancel();
-
- }
- @Override
- protected void onActivityResult(int requestCode, int resultCode, Intent data) {
- // TODO Auto-generated method stub
- super.onActivityResult(requestCode, resultCode, data);
-
- if(requestCode == REQUEST_ENABLE_BT){
- if(resultCode==RESULT_OK){
- //user enable the bluetooth, start search device
- listItems.add("程式已啟動");
- connectDevice();
- }
- }
- }
- private void connectDevice() {
- if(D) Log.e(TAG, "+++ connectDevice() +++");
-
- //Query paired devices
- Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
- // If there are paired devices
- if (pairedDevices.size() > 0) {
-
- // Loop through paired devices
- for (BluetoothDevice device : pairedDevices) {
-
- //connect the device if the device match the bt_hostname
- if(device.getName().equals(bt_hostname)) {
- mBluetoothDevice = device;
- if (D) Log.e(TAG, "+++ connectDevice() - found pairedDevices("+ device.getName() +") +++");
-
- }
-
- }
-
- }
- else {
-
- //Register the BroadcastReceiver
- IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
- registerReceiver(myReceiver,filter);
- //set the flag to unregister the myReceiver when on destroy
- start_discovery = true;
-
- //start to discovery led device
- doDiscovery();
- }
-
- //Create the connection thread
- if (D) Log.e(TAG, "+++ connectDevice() - mBluetoothDevice("+ mBluetoothDevice.getName() +") +++");
- mConnectThread = new ConnectThread(mBluetoothDevice);
- mConnectThread.start();
-
-
- }
- /** Will cancel an in-progress connection, and close the socket */
- public void cancel() {
-
- if (D) Log.e(TAG, "+++ ConnectThread - cancel() ("+ mmDevice.getName() +") +++");
-
- try {
- mmSocket.close();
- } catch (IOException e) { }
- }
-
- }
-
- private class ConnectedThread extends Thread {
- private final BluetoothSocket mmSocket;
- private final InputStream mmInStream;
- private final OutputStream mmOutStream;
- public ConnectedThread(BluetoothSocket socket) {
-
- if (D) Log.e(TAG, "+++ ConnectedThread() +++");
-
- mmSocket = socket;
- InputStream tmpIn = null;
- OutputStream tmpOut = null;
- // Get the input and output streams, using temp objects because
- // member streams are final
- try {
- tmpIn = socket.getInputStream();
- tmpOut = socket.getOutputStream();
- } catch (IOException e) { }
- mmInStream = tmpIn;
- mmOutStream = tmpOut;
- }
- public void run() {//如果需要接收資料的話,把下面的comment 轉為 statement
- /*
- byte[] buffer = new byte[1024]; // buffer store for the stream
- int bytes; // bytes returned from read()
- // Keep listening to the InputStream until an exception occurs
- while (true) {
- try {
- // Read from the InputStream
- bytes = mmInStream.read(buffer);
- // Send the obtained bytes to the UI Activity
- mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer)
- .sendToTarget();
- } catch (IOException e) {
- break;
- }
- }
- */
- write();
- }
- /* Call this from the main Activity to send data to the remote device */
- //public void write(byte[] bytes) {
- public void write() {
- String str = "1234\r\n";
- byte[] bytes = str.getBytes();
-
- if (D) Log.e(TAG, "+++ ConnectedThread - Write() +++");
-
- try {
- mmOutStream.write(bytes);
-
- } catch (IOException e) { }
- }
- /* Call this from the main Activity to shutdown the connection */
- public void cancel() {
- try {
- mmSocket.close();
- } catch (IOException e) { }
- }
- }
-
-
- }
複製代碼 |