- 1、原创力文档(book118)网站文档一经付费(服务费),不意味着购买了该文档的版权,仅供个人/单位学习、研究之用,不得用于商业用途,未经授权,严禁复制、发行、汇编、翻译或者网络传播等,侵权必究。。
- 2、本站所有内容均由合作方或网友上传,本站不对文档的完整性、权威性及其观点立场正确性做任何保证或承诺!文档内容仅供研究参考,付费前请自行鉴别。如您付费,意味着您自己接受本站规则且自行承担风险,本站不退款、不进行额外附加服务;查看《如何避免下载的几个坑》。如果您已付费下载过本站文档,您可以点击 这里二次下载。
- 3、如文档侵犯商业秘密、侵犯著作权、侵犯人身权等,请点击“版权申诉”(推荐),也可以打举报电话:400-050-0827(电话支持时间:9:00-18:30)。
查看更多
Android BLE与终端通信(四)——实现服务器与客户端即时通讯功能
在开始之前,别忘了添加权限
uses-permission android:name=android.permission.BLUETOOTH /
uses-permission android:name=android.permission.BLUETOOTH_ADMIN /
一.OpenBluetooth
Google的API上说的是十分的清楚,我们作为初学者要把他当做说明书一样来看待
这样的话,我们就来实现打开蓝牙并且打开可见性,可见性默认是120s,MAX为3600s,这里在强调一遍,打开蓝牙有两种方式,一种是弹框提示,一种是强制打开,这在之前也是提过好多次了的
/**
* 打开蓝牙并且搜索
*/
public void openBluetooth(View v) {
// 开启搜索
Intent discoverableIntent = new Intent(
BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
// 设置可见性300s
discoverableIntent.putExtra(
BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(discoverableIntent);
// 强制打开
// mBluetoothAdapter.enable();
}
CloseBluetooth
关闭蓝牙也就直接调用BluetoothAdapter的disable()方法;
/**
* 关闭蓝牙
*/
public void closeBluetooth(View v) {
mBluetoothAdapter.disable();
}
客户端
我们在MainActivity中写一个button直接跳转到ClientActivity中去
/**
* 打开客户端
*/
public void Client(View v) {
startActivity(new Intent(this, ClientActivity.class));
}
ClientActivity
package 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.ReceiverInfoThread;
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.text.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 =
文档评论(0)