Download presentation
Presentation is loading. Please wait.
1
Android藍芽聊天室 SDK內的範例程式
建國科技大學 資管系 饒瑞佶 2013/7 V1
2
Android 2.2 SDK
3
Android藍芽聊天室 BluetoothChat.java:主畫面,顯示聊天訊息與設定藍芽
BluetoothChatService.java:藍芽傳輸service,包含三個主要thread: AcceptThread:負責監聽藍芽socket ConnectThread:負責藍芽socket連線 ConnectedThread:藍芽連線後通訊程序 DeviceListActivity.java:搜尋藍芽設備介面
4
AndroidManiFest.xml
5
layout ListView 從下往上顯示 android:stackFromBottom="true" TextView Button
6
BluetoothChat.java onCreate: onStart: onResume:恢復service
判斷設備是否支援藍芽 取得BluetoothAdapter:mBluetoothAdapter onStart: 透過BluetoothAdapter判斷藍芽是否開啟+ onActivityResult() 呼叫setupChat() onResume:恢復service onDestroy:停止service
7
BluetoothChat.java setupChat(): 設定arrayadapter用以顯示對話資訊(對應到listview)
監聽輸入框enter事件(按軟體鍵盤enter也可以送出) mOutEditText.setOnEditorActionListener(mWriteListener); 設定送出按鈕 取得mChatService = new BluetoothChatService(this, mHandler); 取得service對應狀態 BluetoothChatService.java
8
BluetoothChat.java sendMessage: 使用mChatService判斷是否連線 送出資訊
byte[] send = message.getBytes(); mChatService.write(send);
9
BluetoothChat.java onCreateOptionsMenu:建立menu選項
onOptionsItemSelected:設定menu對應事件 掃描:DeviceListActivity.class + onActivityResult() 可被發現:ensureDiscoverable() Handler mHandler:處理對話訊息的進出
10
BluetoothChatService.java 全部共3個thread AcceptThread:負責監聽藍芽socket
/** * This class does all the work for setting up and managing Bluetooth * connections with other devices. It has a thread that listens for * incoming connections, a thread for connecting with a device, and a * thread for performing data transmissions when connected. */ 全部共3個thread AcceptThread:負責監聽藍芽socket ConnectThread:負責藍芽socket連線 ConnectedThread:藍芽連線後通訊程序
11
BluetoothChatService.java 建構子: start():
取得BluetoothAdapter :mAdapter start(): 對應AcceptThread 從BluetoothChat.java的onResume()呼叫 connect(BluetoothDevice device) : 對應ConnectThread 從BluetoothChat.java的onActivityResult內的case REQUEST_CONNECT_DEVICE呼叫 connected(BluetoothSocket socket, BluetoothDevice device) : 從BluetoothChatService.java的AcceptThread呼叫
12
android:theme="@android:style/Theme.Dialog"
DeviceListActivity.java 在AndroidManifest.xml中設定android:theme 將一個Activity顯示為能話框模式
13
android:theme
14
DeviceListActivity.java // Setup the window requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
15
DeviceListActivity.java onCreate: onDestroy()
設定arrayadapter用以顯示配對(mPairedDevicesArrayAdapter)與未配對的設備(mNewDevicesArrayAdapter) 設定BroadcastReceiver(mReceiver),用以接收設備搜尋完畢 取得BluetoothAdapter (mBtAdapter) 設定按鈕進行doDiscovery() onDestroy() 取消BluetoothAdapter (mBtAdapter)
16
DeviceListActivity.java OnItemClickListener: 取得所選設備MAC
intent.putExtra(EXTRA_DEVICE_ADDRESS, address); 回到BluetoothChat.java中的onActivityResult,並取得設備MAC String address = data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
Similar presentations