AndroidBLE与终端通信(四)——实现服务器与客户端即时通讯功能_第1页
AndroidBLE与终端通信(四)——实现服务器与客户端即时通讯功能_第2页
AndroidBLE与终端通信(四)——实现服务器与客户端即时通讯功能_第3页
AndroidBLE与终端通信(四)——实现服务器与客户端即时通讯功能_第4页
AndroidBLE与终端通信(四)——实现服务器与客户端即时通讯功能_第5页
已阅读5页,还剩9页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

1、Android BLE与终端通信(四)实现服务器与客户端即时通讯功能在开始之前,别忘了添加权限<uses-permission android:name="android.permission.BLUETOOTH" /><uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />一.OpenBluetoothGoogle的API上说的是十分的清楚,我们作为初学者要把他当做说明书一样来看待这样的话,我们就来实现打开蓝牙并且打开可见性,可见性默认是120s,

2、MAX为3600s,这里在强调一遍,打开蓝牙有两种方式,一种是弹框提示,一种是强制打开,这在之前也是提过好多次了的/* * 打开蓝牙并且搜索 */ 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关闭蓝牙也就直接调用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; / 发送按钮 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("客户端已经启动,正在与服务端连接.n"); / 开始连接 new Thread(new Runnable() Override public void run() try / 得到本地蓝牙适配器 mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter()

11、; / 通过本地适配器得到地址,这个地址可以公共扫描来获取,就是getAddress()返回的地址 device = mBluetoothAdapter .getRemoteDevice("98:6C:F5:CE:0E:81"); / 根据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(); / 连接成功发送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(); /* * 发送消息 */ 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; / 发送按钮 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(); / 创建蓝牙服务端的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("服务器已经启动,正在等待设备连接.n"); / 开启线程操作 new Thread(new Runnable() Override public void run()

25、/ 得到本地适配器 mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); / 创建蓝牙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(); / 连接成功发送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(); /* * 发送消息 */ 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. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论