蓝牙
蓝牙,是一种支持设备短距离通信(一般10m内,且无阻隔媒介)的无线电技术。能在包括移动电话、PDA、无线耳机、笔记本电脑等众多设备之间进行无线信息交换。利用“蓝牙”技术,能够有效的简化移动通信终端设备之间的通信,也能够成功的简化设备与Internet之间的通信,这样数据传输变得更加迅速高效,为无线通信拓宽道路。

注意:Android 2.0 引入蓝牙接口,在开发时,需要真机测试,如果需要数据传输,还需要两台机器,另外蓝牙下哟硬件支持。

蓝牙设备操作
权限:

<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.BLUETOOTH" />
打开蓝牙的方式有两种:

//第一种方法,打开蓝牙设备(提示对话框)
Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(discoverableIntent);
//第二种方法,打开蓝牙,静默打开
BluetoothAdapter bluetoothAdapter=BluetoothAdapter.getDefaultAdapter();
bluetoothAdapter.enable();
搜索蓝牙设备

//开始扫描蓝牙设备
BluetoothAdapter bluetoothAdapter2=BluetoothAdapter.getDefaultAdapter();
bluetoothAdapter2.startDiscovery();
关闭蓝牙设备

BluetoothAdapter bluetoothAdapter1=BluetoothAdapter.getDefaultAdapter();
bluetoothAdapter1.disable();
 
蓝牙通讯案例

MainActivity.java

package com.example.bluetooth;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import java.util.Set;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Button open, close,button_scan,button_server,button_client;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
open = findViewById(R.id.open);
close = findViewById(R.id.close);
button_scan = findViewById(R.id.button_scan);
button_server = (Button) findViewById(R.id.button_server);
button_client = (Button) findViewById(R.id.button_client);
open.setOnClickListener(this);
close.setOnClickListener(this);
button_scan.setOnClickListener(this);
button_server.setOnClickListener(this);
button_client.setOnClickListener(this);

}

@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.open:
/*//第一种方法,打开蓝牙设备(提示对话框)
Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
//打开本机蓝牙发现功能
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(discoverableIntent);*/

//第二种方法,打开蓝牙,静默打开
BluetoothAdapter bluetoothAdapter=BluetoothAdapter.getDefaultAdapter();
bluetoothAdapter.enable();
break;
case R.id.close:
BluetoothAdapter bluetoothAdapter1=BluetoothAdapter.getDefaultAdapter();
bluetoothAdapter1.disable();
break;
case R.id.button_scan:
//开始扫描蓝牙设备
BluetoothAdapter bluetoothAdapter2=BluetoothAdapter.getDefaultAdapter();
bluetoothAdapter2.startDiscovery();
Log.i("tag","开始扫描蓝牙设备");
Set<BluetoothDevice> set=bluetoothAdapter2.getBondedDevices();
for (BluetoothDevice bd:set){
Log.i("tag","name:"+bd.getName());
Log.i("tag","address:"+bd.getAddress());
}
break;
case R.id.button_server:
Intent intent = new Intent(this, ServerBluetoothActivity.class);
startActivity(intent);
break;
case R.id.button_client:
Intent intent1 = new Intent(this, ClientBluetoothActivity.class);
startActivity(intent1);
break;
default:
break;
}
}
}
ServerBluetoothActivity.java

package com.example.bluetooth;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.lang.ref.WeakReference;
import java.util.UUID;

public class ServerBluetoothActivity extends AppCompatActivity {

private 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 static Button button_send;
private static TextView textView_content;
private static EditText editText_info;
BluetoothAdapter bluetoothAdapter=null;//本地蓝牙设备
BluetoothServerSocket serverSocket=null;//蓝牙设备Socket服务端
BluetoothSocket socket=null;//蓝牙设备Socket客户端

//输入输出流
PrintStream out;
BufferedReader in;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_server_bluetooth);
setTitle("蓝牙服务端");
textView_content= (TextView) findViewById(R.id.textView_content);
editText_info= (EditText) findViewById(R.id.editText_info);
button_send= (Button) findViewById(R.id.button_send);
init();
}

//创建蓝牙服务器端的Socket
private void init() {
textView_content.setText("服务器已启动,正在等待连接...\n");
new Thread(new Runnable() {
@Override
public void run() {
//1.得到本地设备
bluetoothAdapter=BluetoothAdapter.getDefaultAdapter();
//2.创建蓝牙Socket服务器
try {
serverSocket=bluetoothAdapter.listenUsingRfcommWithServiceRecord("text", UUID.fromString("00000000-2527-eef3-ffff-ffffe3160865"));
//3.阻塞等待Socket客户端请求
socket=serverSocket.accept();
if (socket!=null){
out=new PrintStream(socket.getOutputStream());
in=new BufferedReader(new InputStreamReader(socket.getInputStream()));
}
handler.sendEmptyMessage(CONN_SUCCESS);
} catch (IOException e) {
e.printStackTrace();
Message msg=handler.obtainMessage(CONN_FAIL,e.getLocalizedMessage());
handler.sendMessage(msg);
}
}
}).start();
}

//防止内存泄漏 正确的使用方法
private final MyHandler handler = new MyHandler(this);
public class MyHandler extends Handler {
//软引用
WeakReference<ServerBluetoothActivity> weakReference;

public MyHandler(ServerBluetoothActivity activity) {
weakReference=new WeakReference<ServerBluetoothActivity>(activity);
}

@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
ServerBluetoothActivity activity=weakReference.get();
if (activity!=null){
switch (msg.what){
case RECEIVER_INFO:
setInfo(msg.obj.toString()+"\n");
break;
case SET_EDITTEXT_NULL:
editText_info.setText("");
break;
case CONN_SUCCESS:
setInfo("连接成功!\n");
button_send.setEnabled(true);
new Thread(new ReceiverInfoThread()).start();
break;
case CONN_FAIL:
setInfo("连接失败!\n");
setInfo(msg.obj.toString() + "\n");
break;
default:
break;
}
}
}
}
private boolean isReceiver=true;

private class ReceiverInfoThread implements Runnable {
@Override
public void run() {
String info=null;
while (isReceiver){
try {
info=in.readLine();
Message msg=handler.obtainMessage(RECEIVER_INFO,info);
handler.sendMessage(msg);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

public void sendClick(View view){
final String content=editText_info.getText().toString();
if (TextUtils.isEmpty(content)){
Toast.makeText(this, "不能发送空消息", Toast.LENGTH_SHORT).show();
return;
}
new Thread(new Runnable() {
@Override
public void run() {
out.println(content);
out.flush();
handler.sendEmptyMessage(SET_EDITTEXT_NULL);
}
}).start();
}
private void setInfo(String info){
StringBuffer sb=new StringBuffer();
sb.append(textView_content.getText());
sb.append(info);
textView_content.setText(sb);
}
}
ClientBluetoothActivity.java

package com.example.bluetooth;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
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;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.lang.ref.WeakReference;
import java.util.UUID;

public class ClientBluetoothActivity extends AppCompatActivity {
private 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 static Button button_send;
private static TextView textView_content;
private static EditText editText_info;

BluetoothAdapter bluetooth=null;//本地蓝牙设备
BluetoothDevice device=null;//远程蓝牙设备
BluetoothSocket socket=null;//蓝牙设备Socket客户端

//输入输出流
PrintStream out;
BufferedReader in;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_client_bluetooth);

setTitle("蓝牙客户端");
textView_content= (TextView) findViewById(R.id.textView_content);
editText_info= (EditText) findViewById(R.id.editText_info);
button_send= (Button) findViewById(R.id.button_send);
init();
}

//创建蓝牙客户端端的Socket
private void init() {
textView_content.setText("客户端已启动,正在等待连接...\n");
new Thread(new Runnable() {
@Override
public void run() {
//1.得到本地蓝牙设备的默认适配器
bluetooth=BluetoothAdapter.getDefaultAdapter();
//2.通过本地蓝牙设备得到远程蓝牙设备
device=bluetooth.getRemoteDevice("22:22:4E:6E:59:86");
//3.根据UUID创建并返回一个BoluetoothSocket
try {
socket=device.createRfcommSocketToServiceRecord(UUID.fromString("00000000-2527-eef3-ffff-ffffe3160865"));
if (socket!=null) {
// 连接
socket.connect();
//处理客户端输出流
out=new PrintStream(socket.getOutputStream());
in=new BufferedReader(new InputStreamReader(socket.getInputStream()));
}
handler.sendEmptyMessage(CONN_SUCCESS);
} catch (IOException e) {
e.printStackTrace();
Message msg=handler.obtainMessage(CONN_FAIL,e.getLocalizedMessage());
handler.sendMessage(msg);
}
}
}).start();
}
//防止内存泄漏 正确的使用方法
private final MyHandler handler = new MyHandler(this);
public class MyHandler extends Handler {
//软引用
WeakReference<ClientBluetoothActivity> weakReference;

public MyHandler(ClientBluetoothActivity activity) {
weakReference = new WeakReference<ClientBluetoothActivity>(activity);
}

@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
ClientBluetoothActivity activity = weakReference.get();
if (activity!=null){
switch (msg.what){
case RECEIVER_INFO:
setInfo(msg.obj.toString() + "\n");
break;
case SET_EDITTEXT_NULL:
editText_info.setText("");
break;
case CONN_SUCCESS:
setInfo("连接成功!\n");
button_send.setEnabled(true);
System.out.println("name"+device.getName());
System.out.println("Uuids"+device.getUuids());
System.out.println("Address"+device.getAddress());
new Thread(new ReceiverInfoThread()).start();
break;
case CONN_FAIL:
setInfo("连接失败!\n");
setInfo(msg.obj.toString() + "\n");
break;
default:
break;
}
}
}
}
private boolean isReceiver=true;
//接收信息的线程
class ReceiverInfoThread implements Runnable{
@Override
public void run() {
String info=null;
while (isReceiver){
try {
Log.i("tag","--ReceiverInfoThread start --");
info=in.readLine();
Log.i("tag","--ReceiverInfoThread read --");
Message msg=handler.obtainMessage(RECEIVER_INFO,info);
handler.sendMessage(msg);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

public void sendClick(View v){
final String content=editText_info.getText().toString();
if (TextUtils.isEmpty(content)){
Toast.makeText(this, "不能发送空消息", Toast.LENGTH_SHORT).show();
return;
}
new Thread(new Runnable() {
@Override
public void run() {
out.println(content);
out.flush();
handler.sendEmptyMessage(SET_EDITTEXT_NULL);
}
}).start();
}
private void setInfo(String info){
StringBuffer sb=new StringBuffer();
sb.append(textView_content.getText());
sb.append(info);
textView_content.setText(sb);
}

---------------------

Android学习——蓝牙通讯的更多相关文章

  1. android 蓝牙通讯编程 备忘

    1.启动App后: 判断->蓝牙是否打开(所有功能必须在打牙打开的情况下才能用) 已打开: 启动代码中的蓝牙通讯Service 未打开: 发布 打开蓝牙意图(系统),根据Activity返回进场 ...

  2. 【转】Android bluetooth介绍(二): android blueZ蓝牙代码架构及其uart 到rfcomm流程

    原文网址:http://blog.sina.com.cn/s/blog_602c72c50102uzoj.html 关键词:蓝牙blueZ  UART  HCI_UART H4  HCI  L2CAP ...

  3. Android学习路线总结,绝对干货

    title: Android学习路线总结,绝对干货 tags: Android学习路线,Android学习资料,怎么学习android grammar_cjkRuby: true --- 一.前言 不 ...

  4. Android BLE 蓝牙编程(一)

    最近在研究这个,等我有时间来写吧! 终于在端午节给自己放个假,现在就来说说关于android蓝牙ble的 最近的学习成果吧!! 需要材料(写个简单教程吧--关于小米手环的哦!嘿嘿) Android 手 ...

  5. Android 学习资料收集

    收集整理这份资料灵感来自于 trip_to_iOS, 征得同意引用了该资料的开头描述 收集整理这份资料主要帮助初学者学习 Android 开发, 希望能快速帮助到他们快速入门, 找到适合自己学习资料, ...

  6. 十、Android学习第九天——小结(转)

    (转自:http://wenku.baidu.com/view/af39b3164431b90d6c85c72f.html) 十.Android学习第九天——小结 通过这段时间的学习,今晚上来做个小小 ...

  7. Android 学习笔记之网络通信基础+WebView....

    PS:加快学习进度...下周一完成Android网络通信...然后正式进入实战... 学习内容: 1.Android中Http基础... 2.Android中的Socket基础... 3.Androi ...

  8. iOS开发--通过MultipeerConnectivity完成蓝牙通讯

    iOS开发–通过MultipeerConnectivity完成蓝牙通讯 iOS蓝牙通讯的三种方式: GameKit.framework:iOS7之前的蓝牙通讯框架,从iOS7开始过期,但是目前已经被淘 ...

  9. Android学习路线(二十四)ActionBar Fragment运用最佳实践

    转载请注明出处:http://blog.csdn.net/sweetvvck/article/details/38645297 通过前面的几篇博客.大家看到了Google是怎样解释action bar ...

随机推荐

  1. mac下Android Studio干净卸载

    1.卸载Android Studio,在终端(terminal)执行以下命令: rm -Rf /Applications/Android\ Studio.app rm -Rf ~/Library/Pr ...

  2. WIN7 64位升级更新到IE10或IE11后,IE不能打开

    权限问题,已经解决 解决办法: 用regedit打开注册表,找到 HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\Main 对左侧树Mai ...

  3. hdu-4118 Holiday's Accommodation(树形dp+树的重心)

    题目链接: Holiday's Accommodation Time Limit: 8000/4000 MS (Java/Others)     Memory Limit: 200000/200000 ...

  4. 【HDU 1520】 Anniversary Party

    [题目链接] 点击打开链接 [算法] 树形DP 令f[i][0]表示 : 以i为根的子树中,若i不参加宴会,所能获得的最大愉悦值 f[i][1]表示 : 以i为根的子树中,若i参加宴会,所能获得的最大 ...

  5. Bootstrap中的各种下拉菜单

    @*基本下拉菜单与按钮下拉菜单的样式完全一致.不过,基本的下拉菜单使用<div class="dropdown">包裹,所有要换行.而按钮式下拉菜单<div cl ...

  6. OSI模型与TCP/IP模型基础

    一.OSI七层模型 OSI(Open System Interconnection),OSI是一个开放性的通行系统互连参考模型,是一个协议规范.OSI七层模型是一种框架性的设计方法 ,建立七层模型的主 ...

  7. 【转载】SQL面试题

    [本文转自]http://blog.csdn.net/u012467492/article/details/46790205 1.用一条SQL 语句 查询出每门课都大于80 分的学生姓名 name   ...

  8. 【插件开发】—— 11 窃听风云(Java事件监听原理-GEF实例讲解)

    前文回顾: 1 插件学习篇 2 简单的建立插件工程以及模型文件分析 3 利用扩展点,开发透视图 4 SWT编程须知 5 SWT简单控件的使用与布局搭配 6 SWT复杂空间与布局搭配 7 SWT布局详解 ...

  9. nginx下配置虚拟主机

    linux 虚拟机下配置虚拟主机 nginx.conf 文件不动, 在 conf.d 或者 conf 目录下 新建项目.conf server { listen 80; server_name loc ...

  10. SpringBoot使用MongoDB

    一.什么是MongoDB MongoDB是一个基于分布式文件存储的数据库,由C++语言编写.旨在为WEB应用提供可扩展的高性能数据存储解决方案. MongoDB是一个介于关系数据库和非关系数据库之间的 ...