android蓝牙技术
配置权限
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
Xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#0f0"
>
<Button
android:id="@+id/check_bluetooth"
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="检查蓝牙"
/>
<Button
android:id="@+id/open_bluetooth"
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="打开蓝牙"
/>
<Button
android:id="@+id/scan_bluetooth"
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="扫描蓝牙"
/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#00f"
>
<EditText
android:id="@+id/msg"
android:layout_width="120dp"
android:layout_height="wrap_content"
/>
<Button
android:id="@+id/send"
android:layout_width="80dp"
android:layout_height="wrap_content"
android:text="发送"
/>
<TextView
android:id="@+id/showmsg1"
android:layout_width="60dp"
android:layout_height="wrap_content"
android:background="#f00" />
</LinearLayout> <ListView
android:id="@+id/pdbluetooth"
android:layout_width="match_parent"
android:layout_height="0dip"
android:layout_weight="1"
android:background="#f00"
/>
<ListView
android:id="@+id/unpdbluetooth"
android:layout_width="match_parent"
android:layout_height="0dip"
android:layout_weight="1"
/>
</LinearLayout>
MainActivity

package com.ch.day15_bluetooth; import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Set;
import java.util.UUID; import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast; public class MainActivity extends Activity implements OnItemClickListener{
public static UUID uuid = UUID.fromString("00001001-0000-1000-8000-00805F9B34FB");
private Button check,open,scan;
private EditText msg;
private Button send;
private TextView showmsg;
//蓝牙显示的列表
private ListView pdbluetooth,unpdbluetooth;
//蓝牙显示的列表的适配器
private ArrayAdapter<String> pdAdapter,unpdAdapter; private BluetoothAdapter bluetoothAdapter;
private Context mcontext;
//声明集合,保存配对过的蓝牙,和没有配对过
private ArrayList<BluetoothDevice> pdbluetoothDevices,unpdbluetoothDevices;
//定义一个蓝牙的输出流
OutputStream output; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mcontext = this;
init();
}
//接收其他的蓝牙给本手机发送的信息的线程,传递信息到这个handler,显示在主线程的ui上
Handler handler = new Handler(){
public void handleMessage(android.os.Message msg) {
showmsg.setText((String)msg.obj);
};
}; public void init(){
check = (Button) findViewById(R.id.check_bluetooth);
open = (Button) findViewById(R.id.open_bluetooth);
scan = (Button) findViewById(R.id.scan_bluetooth);
//添加单击监听
check.setOnClickListener(clickLis);
open.setOnClickListener(clickLis);
scan.setOnClickListener(clickLis);
//获得发送信息区域
msg = (EditText) findViewById(R.id.msg);
send = (Button) findViewById(R.id.send);
showmsg = (TextView) findViewById(R.id.showmsg1);
send.setOnClickListener(clickLis); //获得listview
pdbluetooth = (ListView) findViewById(R.id.pdbluetooth);
unpdbluetooth = (ListView) findViewById(R.id.unpdbluetooth);
//创建listview的适配器
pdAdapter = new ArrayAdapter<String>(mcontext, android.R.layout.simple_list_item_1);
unpdAdapter = new ArrayAdapter<String>(mcontext, android.R.layout.simple_list_item_1);
//把适配器,添加给Listview
pdbluetooth.setAdapter(pdAdapter);
unpdbluetooth.setAdapter(unpdAdapter);
//给listview添加点击事件
pdbluetooth.setOnItemClickListener(this);
unpdbluetooth.setOnItemClickListener(this); //创建保存蓝牙的集合
pdbluetoothDevices = new ArrayList<BluetoothDevice>();
unpdbluetoothDevices = new ArrayList<BluetoothDevice>(); //开启接收蓝牙信息的线程
new BlueAcceptThread(mcontext, handler).start();
} OnClickListener clickLis = new OnClickListener() {
@Override
public void onClick(View v) {
switch (v.getId()) {
//检查蓝牙设置是否有
case R.id.check_bluetooth:
//获得蓝牙适配器,没有表示没有蓝牙设备
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if(bluetoothAdapter != null){
Toast.makeText(mcontext, "支持蓝牙!", 0).show();
}else{
Toast.makeText(mcontext, "没有蓝牙设备!", 0).show();
}
break; case R.id.open_bluetooth:
if(bluetoothAdapter != null){
if(!bluetoothAdapter.enable()){//蓝牙设备可不用,未打开
bluetoothAdapter.enable();//打开蓝牙 // 通过启动相关Activity打开
// Intent it = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
// startActivity(it);
}
//设置蓝牙可见的时间长度为300秒
Intent it = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
it.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 600);
startActivity(it);
}else{
Toast.makeText(mcontext, "检查是否支持蓝牙!", 0).show();
}
break; case R.id.scan_bluetooth:
pdbluetoothDevices.clear();//清空就得配对蓝牙
unpdbluetoothDevices.clear();//再一次扫描蓝牙,清空旧的未配对蓝牙列表信息
pdAdapter.clear();
unpdAdapter.clear(); if(bluetoothAdapter != null){
//如果正在扫描,关闭扫描,重新扫描
if(bluetoothAdapter.isDiscovering()){
bluetoothAdapter.cancelDiscovery();
} //获得已经配对过得蓝牙设备
Set<BluetoothDevice> devices = bluetoothAdapter.getBondedDevices();
if(devices.size() > 0){//有配对的蓝牙 //遍历配对过得蓝牙
for(BluetoothDevice device:devices){
pdbluetoothDevices.add(device);//收集配对的蓝牙
pdAdapter.add(device.getName()+"---"+device.getAddress());//把蓝牙的信息给listview的适配器
}
}
//注册接收扫描到蓝牙的广播,从中获得扫描到的蓝牙
IntentFilter filter1 = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(receiver, filter1);
//注册扫描完成的广播
IntentFilter filter2 = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(receiver, filter2);
//重新扫描所以蓝牙
bluetoothAdapter.startDiscovery(); }else{
Toast.makeText(mcontext, "检查是否支持蓝牙!", 0).show();
}
break; case R.id.send:
if(output != null){
String msgdata = msg.getText().toString();
FileInputStream fis = null;
try {
//发送信息到刚刚连接的蓝牙
output.write(msgdata.getBytes());
fis = new FileInputStream("/nmt/sdcard/360sicheck.txt");
int length = fis.available();
byte[] buffer = new byte[length];
fis.read(buffer);
output.write(buffer);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}else{
Toast.makeText(mcontext, "请先选择一个蓝牙!", 0).show();
}
break;
default:
break;
} }
}; /**
* 此广播用来接收扫描到蓝牙的广播
*/
BroadcastReceiver receiver = new BroadcastReceiver(){ @Override
public void onReceive(Context context, Intent intent) {
//接受扫描到的蓝牙
String action = intent.getAction();//得到广播的动作(类型)
if(action.equals(BluetoothDevice.ACTION_FOUND)){//扫描到蓝牙的广播
//获得扫描到的蓝牙
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
//此蓝牙没有绑定过(配对过)
if(device.getBondState() != BluetoothDevice.BOND_BONDED){
unpdbluetoothDevices.add(device);//收集未绑定的蓝牙
unpdAdapter.add(device.getName()+"---"+device.getAddress());//未绑定的蓝牙的listview的适配器
} }else if(action.equals(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)){
Toast.makeText(mcontext, "扫描完成!", 0).show();
} } }; /**
* lisrview的点击事件监听器
*/
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
switch (parent.getId()) {
case R.id.pdbluetooth://点击的是配对过的listview
pairOrConnectionDevice(pdbluetoothDevices.get(position));//操作配对过的蓝牙
break;
case R.id.unpdbluetooth://点击的是没有配对过的listview
pairOrConnectionDevice(unpdbluetoothDevices.get(position));//操作没有配对过的蓝牙
break; default:
break;
} } /**
* 此方法负责处理蓝牙,配对或直接连接
* @param bluetoothDevice
*/
private void pairOrConnectionDevice(BluetoothDevice bluetoothDevice) {
int state = bluetoothDevice.getBondState();//获得
if(state == BluetoothDevice.BOND_NONE){//还没有配对,进行配对
try {
//通过反射,设置此蓝牙为绑定状态
Method method = BluetoothDevice.class.getMethod("createBond");
method.invoke(bluetoothDevice);
Toast.makeText(mcontext, bluetoothDevice.getName()+",配对成功!", 0).show();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(mcontext, bluetoothDevice.getName()+",配对失败!", 0).show();
}
}else if(state == BluetoothDevice.BOND_BONDED){//配对过的,进行连接
new BlueToothConnection(bluetoothDevice).start();
}
}
/**
* 此线程用于为蓝牙建立连接,发送信息
* @author hchen
*
*/
class BlueToothConnection extends Thread{
BluetoothDevice device;
BluetoothSocket bluetoothSocket;
public BlueToothConnection(BluetoothDevice device) {
super();
this.device = device;
} @Override
public void run() {
Looper.prepare();//发送信息前的准备
try {
//创建此蓝牙的客户端,通过客户端可以向它传递数据
bluetoothSocket = device.createRfcommSocketToServiceRecord(uuid);
//连接
System.out.println("000000000000000");
bluetoothSocket.connect();
System.out.println("1111111111111111111");
//创建此蓝牙的具体的输出流
output = bluetoothSocket.getOutputStream();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Looper.loop();
}
} }

BlueAcceptThread

package com.ch.day15_bluetooth; import java.io.IOException;
import java.io.InputStream; import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.os.Handler;
import android.util.Log; public class BlueAcceptThread extends Thread{
private Context mcontext;
private Handler handler; private BluetoothAdapter bluetoothAdapter;
BluetoothServerSocket bluetoothServerSocket;
BluetoothSocket bluetoothSocket;
InputStream input;
public BlueAcceptThread(Context mcontext,Handler handler) {
super();
this.mcontext = mcontext;
this.handler = handler; bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
}
@Override
public void run() {
if(bluetoothAdapter != null){
try {
//创建本手机的蓝牙的服务器
bluetoothServerSocket = bluetoothAdapter.listenUsingRfcommWithServiceRecord("mybluetooth", MainActivity.uuid);
//接收一个蓝牙客户端
Log.i("TAG","准备.....接收一个......................");
bluetoothSocket = bluetoothServerSocket.accept();
Log.i("TAG","接收了一个......................");
//得到连接我的那个一方的输入流
input = bluetoothSocket.getInputStream();
byte[] buffer = new byte[1024];
//读取数据,循环多次,因为有多条
while(true){
//读取当前这一条
int length = input.read(buffer);
String getData = new String(buffer,0,length);
Log.i("TAG","接收信息.........."+getData);
handler.sendMessage(handler.obtainMessage(0x123, getData));
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
android蓝牙技术的更多相关文章
- Android 蓝牙技术 实现终端间数据传输
蓝牙技术在智能硬件方面有很多用武之地,今天我就为大家分享一下蓝牙技术在Android系统下的使用方法技巧.蓝牙是一种短距离的无线通信技术标准,蓝牙协议分为4层,即核心协议层.电缆替代协议层.电话控制协 ...
- Android蓝牙技术Bluetooth使用流程(具体解释)
一:蓝牙设备之间的通信主要包含了四个步骤 设置蓝牙设备 寻找局域网内可能或者匹配的设备 连接设备 设备之间的传输数据 二:详细编程实现 1. 启动蓝牙功能 首先通过调用静态方法getDefaultAd ...
- android 蓝牙低耗能(LBE)技术介绍
蓝牙低能耗(BLE)技术是低成本.短距离.可互操作的鲁棒性无线技术.工作在免许可的2.4GHz ISM射频频段.它从一開始就设计为超低功耗(ULP)无线技术. 它利用很多智能手段最大限度地减少功耗. ...
- android蓝牙打印机
您还未登录!|登录|注册|帮助 首页 业界 移动 云计算 研发 论坛 博客 下载 更多 reality_jie的专栏 编程的过程是一种微妙的享受 目录视图 摘要视图 订阅 CSDN2013 ...
- NFC(13)使用Android Beam技术传输文件
注意 Android Beam技术传输文件时nfc只负责连接两个手机,而传输文件实际是用蓝牙模块.且目前接收文件功能只是系统完成,不用自写个接收程序. 传输文件相关的重要api 从Android4.1 ...
- NFC(12)使用Android Beam技术传输文本数据及它是什么
Android Beam技术是什么 Android Beam的基本理念就是两部(只能是1对1,不可像蓝牙那样1对多)NFC设备靠近时(一般是背靠背),通过触摸一部NFC设备的屏幕,将数据推向另外一部N ...
- Android 蓝牙开发(整理大全)
Android蓝牙开发 鉴于国内Android蓝牙开发的例子很少,以及蓝牙开发也比较少用到,所以找的资料不是很全. (一): 由于Android蓝牙的通信都需要用到UUID,如果由手机发起搜索,当搜索 ...
- 深入了解Android蓝牙Bluetooth——《基础篇》
什么是蓝牙? 也可以说是蓝牙技术.所谓蓝牙(Bluetooth)技术,实际上是一种短距离无线电技术,是由爱立信公司公司发明的.利用"蓝牙"技术,能够有效地简化掌上电脑.笔记本电 ...
- 【Android应用开发】Android 蓝牙低功耗 (BLE) ( 第一篇 . 概述 . 蓝牙低功耗文档 翻译)
转载请注明出处 : http://blog.csdn.net/shulianghan/article/details/50515359 参考 : -- 官方文档 : https://develope ...
随机推荐
- LeetCode Inorder Successor in BST
原题链接在这里:https://leetcode.com/problems/inorder-successor-in-bst/ Given a binary search tree and a nod ...
- 圆角边框_css控制形状
border-radius:500px 来让整个图像变成圆形. border-top-left-radius: 6px;(左上角圆角) border-top-right-radius: 6px;( ...
- 如何在APICloud平台使用腾讯X5引擎
目前APICloud与腾讯X5引擎已经达成全方位的深度合作,APICloud在多个产品线深度集成X5引擎,广大APICloud开发者们即日起可通过以下几方面在你的APP中使用X5引擎,享受X5引擎带来 ...
- Inside Kolla - 04 Kolla 目录结构
Kolla 目录结构 把 Kolla 的源代码下载下来后,先从总体上分析 Kolla 的目录结构,查看顶层目录结构,使用 tree -L 1 输出 . ├── ansible ├── compose ...
- .Net内存优化的几点经验
以前从来没有想过.Net开发居然存在内存无法释放的问题,总是认为GC给我处理好了一切.现在GIS二次开发结合三维球开发,没有想到存在如此严重的内存增长,很快内存就不够用了,导致系统各种不稳定.球体和三 ...
- UIPickerView详解
一.UIPickerView 1.UIPickerView的常见属性 // 数据源(用来告诉UIPickerView有多少列多少行) @property(nonatomic,assign) id< ...
- Java基础之处理事件——应用程序中的语义事件监听器(Sketcher 5 with element color listeners)
控制台程序. 为了标识元素的类型,可以为菜单已提供的4中元素定义常量,用作ID.这有助于执行菜单项监听器的操作,还提供了一种标识颜色类型的方式.我们会累积许多应用程序范围的常量,所以把它们定义为可以静 ...
- Siverlight去掉ToolTip的白色边框
control作为tooltip后,外框背景是白色的,并且有边框. 我们可以定义 一个样式去掉. <Style x:Key="ToolTipTransparentStyle" ...
- Leetcode: Guess Number Higher or Lower II
e are playing the Guess Game. The game is as follows: I pick a number from 1 to n. You have to guess ...
- G面经prepare: Maximum Subsequence in Another String's Order
求string str1中含有string str2 order的 subsequence 的最小长度 DP做法:dp[i][j]定义为pattern对应到i位置,string对应到j位置时,shor ...