




版權說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權,請進行舉報或認領
文檔簡介
1、Android BLE與終端通信(四)實現(xiàn)服務器與客戶端即時通訊功能在開始之前,別忘了添加權限<uses-permission android:name="android.permission.BLUETOOTH" /><uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />一.OpenBluetoothGoogle的API上說的是十分的清楚,我們作為初學者要把他當做說明書一樣來看待這樣的話,我們就來實現(xiàn)打開藍牙并且打開可見性,可見性默認是120s,
2、MAX為3600s,這里在強調(diào)一遍,打開藍牙有兩種方式,一種是彈框提示,一種是強制打開,這在之前也是提過好多次了的/* * 打開藍牙并且搜索 */ public void openBluetooth(View v) / 開啟搜索 Intent discoverableIntent = new Intent( BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE); / 設置可見性300s discoverableIntent.putExtra( BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300); start
3、Activity(discoverableIntent); / 強制打開 / mBluetoothAdapter.enable(); CloseBluetooth關閉藍牙也就直接調(diào)用BluetoothAdapter的disable()方法; /* * 關閉藍牙 */ public void closeBluetooth(View v) mBluetoothAdapter.disable(); 客戶端我們在MainActivity中寫一個button直接跳轉到ClientActivity中去 /* * 打開客戶端 */ public void Client(View v) startActivi
4、ty(new Intent(this, ClientActivity.class); ClientActivitypackage com.example.ble_qq;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.io.PrintStream;import .SocketOptions;import java.util.UUID;import com.example.ble_qq.ServiceActivity.ReceiverInfoT
5、hread;import android.app.Activity;import android.bluetooth.BluetoothAdapter;import android.bluetooth.BluetoothDevice;import android.bluetooth.BluetoothServerSocket;import android.bluetooth.BluetoothSocket;import android.os.Bundle;import android.os.Handler;import android.os.Message;import android.tex
6、t.TextUtils;import android.util.Log;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.TextView;import android.widget.Toast;/* * 客戶端 * * author LGL * */public class ClientActivity extends Activity / 連接成功 private static final int CONN_SUCCESS =
7、0x1; / 連接失敗 private static final int CONN_FAIL = 0x2; private static final int RECEIVER_INFO = 0x3; / 設置文本框為空 private static final int SET_EDITTEXT_NULL = 0x4; / 接收到的消息 private TextView tv_content; / 輸入框 private EditText et_info; / 發(fā)送按鈕 private Button btn_send; / 本地藍牙適配器 private BluetoothAdapter mBl
8、uetoothAdapter = null; / 遠程設備 private BluetoothDevice device = null; / 藍牙設備Socket客戶端 private BluetoothSocket socket = null; private boolean isReceiver = true; / 設備名稱 private static final String NAME = "LGL" / 輸入輸出流 private PrintStream out; private BufferedReader in; Override protected void
9、 onCreate(Bundle savedInstanceState) / TODO Auto-generated method stub super.onCreate(savedInstanceState); setTitle("客戶端"); setContentView(R.layout.activity_client); initView(); / 初始化Socket客戶端連接 init(); private void initView() / 初始化 tv_content = (TextView) findViewById(R.id.tv_content); et
10、_info = (EditText) findViewById(R.id.et_info); btn_send = (Button) findViewById(R.id.btn_send); private void init() tv_content.setText("客戶端已經(jīng)啟動,正在與服務端連接.n"); / 開始連接 new Thread(new Runnable() Override public void run() try / 得到本地藍牙適配器 mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter()
11、; / 通過本地適配器得到地址,這個地址可以公共掃描來獲取,就是getAddress()返回的地址 device = mBluetoothAdapter .getRemoteDevice("98:6C:F5:CE:0E:81"); / 根據(jù)UUID返回一個socket,要與服務器的UUID一致 socket = device.createRfcommSocketToServiceRecord(UUID .fromString("00000000-2527-eef3-ffff-ffffe3160865"); if (socket != null) / 連接
12、 socket.connect(); / 處理流 out = new PrintStream(socket.getOutputStream(); in = new BufferedReader(new InputStreamReader(socket .getInputStream(); / 連接成功發(fā)送handler handler.sendEmptyMessage(CONN_SUCCESS); catch (IOException e) / TODO Auto-generated catch block e.printStackTrace(); Message mes = handler.
13、obtainMessage(CONN_FAIL, e.getLocalizedMessage(); handler.sendMessage(mes); ).start(); /* * Handler接收消息 * */ private Handler handler = new Handler() public void handleMessage(Message msg) switch (msg.what) case CONN_SUCCESS: setInfo("連接成功! n"); btn_send.setEnabled(true); Log.i("設備的名稱&
14、quot;, device.getName(); Log.i("設備的UUID", device.getUuids() + ""); Log.i("設備的地址", device.getAddress(); / 開始接收信息 new Thread(new ReceiverInfoThread().start(); break; case CONN_FAIL: setInfo("連接失敗! n"); setInfo(msg.obj.toString() + "n"); break; case REC
15、EIVER_INFO: setInfo(msg.obj.toString() + "n"); break; case SET_EDITTEXT_NULL: et_info.setText(""); break; ; /* * 接收消息的線程 */ class ReceiverInfoThread implements Runnable Override public void run() String info = null; while (isReceiver) try info = in.readLine(); Message msg = handl
16、er.obtainMessage(RECEIVER_INFO); handler.sendMessage(msg); catch (IOException e) / TODO Auto-generated catch block e.printStackTrace(); /* * 發(fā)送消息 */ public void SendText(View v) final String text = et_info.getText().toString(); / 不能為空 if (!TextUtils.isEmpty(text) Toast.makeText(this, "不能為空"
17、;, Toast.LENGTH_SHORT).show(); new Thread(new Runnable() Override public void run() / 輸出 out.println(text); out.flush(); / 把文本框設置為空 handler.sendEmptyMessage(SET_EDITTEXT_NULL); ).start(); /* * 拼接文本信息 */ private void setInfo(String info) StringBuffer sb = new StringBuffer(); sb.append(tv_content.getT
18、ext(); sb.append(info); tv_content.setText(sb); 服務端我們在MainActivity中寫一個button直接跳轉到ServiceActivity中去 /* * 打開服務端 */ public void Service(View v) startActivity(new Intent(this, ServiceActivity.class); ServiceActivitypackage com.example.ble_qq;import java.io.BufferedReader;import java.io.IOException;impor
19、t java.io.InputStreamReader;import java.io.PrintStream;import java.util.UUID;import android.app.Activity;import android.bluetooth.BluetoothAdapter;import android.bluetooth.BluetoothServerSocket;import android.bluetooth.BluetoothSocket;import android.os.Bundle;import android.os.Handler;import android
20、.os.IBinder;import android.os.Message;import android.text.TextUtils;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.TextView;import android.widget.Toast;/* * 服務端 * * author LGL * */public class ServiceActivity extends Activity / 連接成功 private
21、 static final int CONN_SUCCESS = 0x1; / 連接失敗 private static final int CONN_FAIL = 0x2; private static final int RECEIVER_INFO = 0x3; / 設置文本框為空 private static final int SET_EDITTEXT_NULL = 0x4; / 接收到的消息 private TextView tv_content; / 輸入框 private EditText et_info; / 發(fā)送按鈕 private Button btn_send; / 本地藍
22、牙適配器 private BluetoothAdapter mBluetoothAdapter = null; / 藍牙設備Socket服務端 private BluetoothServerSocket serviceSocket = null; / 藍牙設備Socket客戶端 private BluetoothSocket socket = null; / 設備名稱 private static final String NAME = "LGL" private boolean isReceiver = true; / 輸入輸出流 private PrintStream
23、out; private BufferedReader in; Override protected void onCreate(Bundle savedInstanceState) / TODO Auto-generated method stub super.onCreate(savedInstanceState); setTitle("服務端"); setContentView(R.layout.activity_service); initView(); / 創(chuàng)建藍牙服務端的Socket initService(); private void initView()
24、/ 初始化 tv_content = (TextView) findViewById(R.id.tv_content); et_info = (EditText) findViewById(R.id.et_info); btn_send = (Button) findViewById(R.id.btn_send); private void initService() tv_content.setText("服務器已經(jīng)啟動,正在等待設備連接.n"); / 開啟線程操作 new Thread(new Runnable() Override public void run()
25、/ 得到本地適配器 mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); / 創(chuàng)建藍牙Socket服務端 try / 服務端地址 serviceSocket = mBluetoothAdapter .listenUsingInsecureRfcommWithServiceRecord( NAME, UUID.fromString("00000000-2527-eef3-ffff-ffffe3160865"); / 阻塞線程等待連接 socket = serviceSocket.accept(); if (sock
26、et != null) / I/O流 out = new PrintStream(socket.getOutputStream(); in = new BufferedReader(new InputStreamReader(socket .getInputStream(); / 連接成功發(fā)送handler handler.sendEmptyMessage(CONN_SUCCESS); catch (IOException e) / TODO Auto-generated catch block e.printStackTace(); Message mes = handler.obtainM
27、essage(CONN_FAIL, e.getLocalizedMessage(); handler.sendMessage(mes); ).start(); /* * Handler接收消息 * */ private Handler handler = new Handler() public void handleMessage(Message msg) switch (msg.what) case CONN_SUCCESS: setInfo("連接成功! n"); btn_send.setEnabled(true); new Thread(new ReceiverIn
28、foThread().start(); break; case CONN_FAIL: setInfo("連接失敗! n"); setInfo(msg.obj.toString() + "n"); break; case RECEIVER_INFO: setInfo(msg.obj.toString() + "n"); break; case SET_EDITTEXT_NULL: et_info.setText(""); break; ; /* * 接收消息的線程 */ class ReceiverInfoThrea
29、d implements Runnable Override public void run() String info = null; while (isReceiver) try info = in.readLine(); Message msg = handler.obtainMessage(RECEIVER_INFO); handler.sendMessage(msg); catch (IOException e) / TODO Auto-generated catch block e.printStackTrace(); /* * 發(fā)送消息 */ public void SendTe
30、xt(View v) final String text = et_info.getText().toString(); / 不能為空 if (!TextUtils.isEmpty(text) Toast.makeText(this, "不能為空", Toast.LENGTH_SHORT).show(); new Thread(new Runnable() Override public void run() / 輸出 out.println(text); out.flush(); / 把文本框設置為空 handler.sendEmptyMessage(SET_EDITTEXT_NULL); ).start(); /* * 拼接
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預覽,若沒有圖紙預覽就沒有圖紙。
- 4. 未經(jīng)權益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負責。
- 6. 下載文件中如有侵權或不適當內(nèi)容,請與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- JJF 2194-2025氧化鋅避雷器測試儀校準規(guī)范
- LY/T 3350-2023展平竹砧板
- 2025至2030年中國半胱胺酒石酸鹽數(shù)據(jù)監(jiān)測研究報告
- 2025年軍隊文職人員招聘之軍隊文職管理學與服務通關題庫(附帶答案)
- 2025年消防設施操作員之消防設備基礎知識強化訓練試卷A卷附答案
- 模擬卷浙江寧波2025屆高三一模語文試題及答案
- (一模)哈三中2025屆高三第一次模擬考試 語文試題(含答案)
- 公司管理理念宣傳手冊(講座內(nèi)容)
- 中學生讀書勵志征文
- 化工圖標知識培訓課件
- 《金融反欺詐與大數(shù)據(jù)風控研究報告(2023)》
- 梨狀窩囊腫的護理查房
- GB/T 15558.1-2023燃氣用埋地聚乙烯(PE)管道系統(tǒng)第1部分:總則
- 公路工程安全風險辨識與防控手冊
- 實驗室安全檢查表
- 初中政治答題卡模板A4
- 供應商滿意度調(diào)查表
- 無圍標、串標行為承諾書
- 第三次全國國土調(diào)查土地分類
- 發(fā)展?jié)h語初級綜合1電子版
- 某鐵路注漿處理工藝性試驗方案
評論
0/150
提交評論