配置权限

<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. Interview with BOA

    1. BFS 2. QuickSort 3. PCA, 1000 articles, so many factors, how to reduce factors. 4. newton's metho ...

  2. dede完美分页样式

    html <div class="dede_pages">              <ul class="pagelist">     ...

  3. 获取dom元素的宽度和高度

    一.获取css的大小 1.第一种通过内联样式 var box = document.getElementById('box'); var w = box.style.width; var h = bo ...

  4. iOS面试题及答案2015.6.7

    iOS面试题及答案     1. Object-c的类可以多重继承么?可以实现多个接口么?Category是什么?重写一个类的方式用继承好还是分类好?为什么? 答: Object-c的类不可以多重继承 ...

  5. 网页flv下载探索_1

    最近看了一个优酷视频(非优酷网站,最终地址指向优酷),用chrome开发者工具,可找到flv地址如下,简单摘录如下: http://27.221.100.104/657D4D2878C3382C781 ...

  6. [SharpMap]二叉树索引

    读取shp文件建立二叉树索引的基本思路分析: /// <summary> /// Generates a spatial index for a specified shape file. ...

  7. C#并发处理-锁OR线程安全?

    每次写博客,第一句话都是这样的:程序员很苦逼,除了会写程序,还得会写博客! 当然,题外话说多了,咱进入正题! 背景 基于任务的程序设计.命令式数据并行和任务并行都要求能够支持并发更新的数组.列表和集合 ...

  8. json数据传输有感

    必须把object对象o给JSON.stringify(o) json字符串化 传到后台 前台js的对象某属性如果是Array  那后台就是Long[] idsArray  这种bean的属性对应 然 ...

  9. From Disk partition to PostgreSQL installation

    From Disk partition to PostgreSQLinstallation [root@compute mnt]# fdisk /dev/sdb Welcome to fdisk (u ...

  10. FB面经prepare: Task Schedule

    每种task都有冷却时间,比如task1执行后,要经过interval时间后才能再次执行,求总共所需时间. 用HashMap保存每一个task的下一次可以开始执行的最早时间 package TaskS ...