配置权限

<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蓝牙技术的更多相关文章

  1. Android 蓝牙技术 实现终端间数据传输

    蓝牙技术在智能硬件方面有很多用武之地,今天我就为大家分享一下蓝牙技术在Android系统下的使用方法技巧.蓝牙是一种短距离的无线通信技术标准,蓝牙协议分为4层,即核心协议层.电缆替代协议层.电话控制协 ...

  2. Android蓝牙技术Bluetooth使用流程(具体解释)

    一:蓝牙设备之间的通信主要包含了四个步骤 设置蓝牙设备 寻找局域网内可能或者匹配的设备 连接设备 设备之间的传输数据 二:详细编程实现 1. 启动蓝牙功能 首先通过调用静态方法getDefaultAd ...

  3. android 蓝牙低耗能(LBE)技术介绍

    蓝牙低能耗(BLE)技术是低成本.短距离.可互操作的鲁棒性无线技术.工作在免许可的2.4GHz ISM射频频段.它从一開始就设计为超低功耗(ULP)无线技术. 它利用很多智能手段最大限度地减少功耗. ...

  4. android蓝牙打印机

    您还未登录!|登录|注册|帮助 首页 业界 移动 云计算 研发 论坛 博客 下载 更多 reality_jie的专栏 编程的过程是一种微妙的享受       目录视图 摘要视图 订阅 CSDN2013 ...

  5. NFC(13)使用Android Beam技术传输文件

    注意 Android Beam技术传输文件时nfc只负责连接两个手机,而传输文件实际是用蓝牙模块.且目前接收文件功能只是系统完成,不用自写个接收程序. 传输文件相关的重要api 从Android4.1 ...

  6. NFC(12)使用Android Beam技术传输文本数据及它是什么

    Android Beam技术是什么 Android Beam的基本理念就是两部(只能是1对1,不可像蓝牙那样1对多)NFC设备靠近时(一般是背靠背),通过触摸一部NFC设备的屏幕,将数据推向另外一部N ...

  7. Android 蓝牙开发(整理大全)

    Android蓝牙开发 鉴于国内Android蓝牙开发的例子很少,以及蓝牙开发也比较少用到,所以找的资料不是很全. (一): 由于Android蓝牙的通信都需要用到UUID,如果由手机发起搜索,当搜索 ...

  8. 深入了解Android蓝牙Bluetooth——《基础篇》

    什么是蓝牙?   也可以说是蓝牙技术.所谓蓝牙(Bluetooth)技术,实际上是一种短距离无线电技术,是由爱立信公司公司发明的.利用"蓝牙"技术,能够有效地简化掌上电脑.笔记本电 ...

  9. 【Android应用开发】Android 蓝牙低功耗 (BLE) ( 第一篇 . 概述 . 蓝牙低功耗文档 翻译)

    转载请注明出处 : http://blog.csdn.net/shulianghan/article/details/50515359 参考 :  -- 官方文档 : https://develope ...

随机推荐

  1. error = Error Domain=NSCocoaErrorDomain Code=3840

    json解析,同样的请求,有一个请求,无反应.纠结了几天,终于解决了. error = Error Domain=NSCocoaErrorDomain Code=3840 "Unescape ...

  2. iOS Block传值

    上个月,针对block恶补了一下,以为自己全部掌握了,其实不尽然. 昨天项目中在下载的时候用到,自己竟然不知道该从何下手,惭愧~ 情景是这个样子的:我写了个下载类,阴老师在调用时,将参数(sid,UR ...

  3. 使用sql语句查询日期在一定时间内的数据

    使用sql语句查询日期在一周内的数据 select * from ShopOrder where datediff(week,ordTime,getdate()-1)=0   //查询当天日期在一周年 ...

  4. sed 例子

    sed 应用示例 给1.1.1.1后面增加2.2.2.2: sed -i 's/Server=1.1.1.1/&,2.2.2.2/g' zabbix_agentd.conf

  5. iOS:访问地址薄

    地址簿的访问 介绍: 地址簿(Address Book)是一个共享的联系人信息数据库.任何iOS应用程序都可以使用.通过提供常用联系人信息,而不是让每一个应用程序管理独立的联系人列表,可改善用户体验. ...

  6. Linux就这个范儿 第13章 打通任督二脉

    Linux就这个范儿 第13章 打通任督二脉 0111010110……你有没有想过,数据从看得见或看不见的线缆上飞来飞去,是怎么实现的呢?数据传输业务的未来又在哪里?在前面两章中我们学习了Linux网 ...

  7. Oracle ORA-12519: TNS:no appropriate service handler found 解决

    有时候连得上数据库,有时候又连不上. 可能是数据库上当前的连接数目已经超过了它能够处理的最大值. select count(*) from v$process --当前的连接数select value ...

  8. ionic 上拉加载更多&瀑布流加载&滚动到底部加载更多 主意事项

    首先下拉刷新的代码是这样的,标红的地方为关键代码 <html> <head> <meta charset="utf-8"> <meta n ...

  9. Java控制语句——while语句

    while循环 在循环刚开始时,会计算一次“布尔表达式”的值,若条件为真,执行循环体,而对于后来每一次额外的循环,都会在开始前重新计算一次. 注意:语句中应有使循环趋向于结束的语句,否则会出现无限循环 ...

  10. ios数字转emoj表情

    +(NSString *)convertSimpleUnicodeStr:(NSString *)inputStr{ ,); UTF32Char inputChar = ; // unicodeInt ...