这篇文章分为两部分:
第一部分:使用系统自身带的蓝牙功能,直接用intent调用就可以
private void sendFile(FileInfo fileInfo){
Intent intent = new Intent();
intent.setAction(Intent.ACTION_SEND);
//这个类型函数是自己工具类的方法,你可以自己设置文件类型,例如图片文件:image/*
//不想写类型直接*/*也是可以的
String type = UtilFileClassify.getMIMEType(fileInfo.fileName);
intent.setType(type);
//这里setClassName就是指定蓝牙,不写这句就弹出选择用什么发送
//有蓝牙啊,gmail啊,彩信之类的
intent.setClassName("com.android.bluetooth"
, "com.android.bluetooth.opp.BluetoothOppLauncherActivity");
intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(
new File(fileInfo.filePath)));
startActivity(intent);
}
需注意的是android系统好像不愿意你蓝牙传送apk,如果你传送会显示失败。
在网上看到传送方式有两种,我去试验下那个蓝牙用stream方式可不可以传送apk
第二部分:用BluetoothAdapter那一系列的操作自己写server 以及 client
1.获取本机的蓝牙适配器:
BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();//获取本机蓝牙适配器
if(btAdapter == null){
Log.e("","there isnt any blouetooth in your device!");
return;
}
2.打开蓝牙适配器:
if(!btAdapter.isEnable){
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivity(intent);
}
3.获取已经配对的蓝牙设备:
Set pairedDevices = btAdapter.getBondedDevice();
for(int i = o;i BluetoothDevice btDevice = pairedDevice.get(i);
String str = "Name:"+btDevice.getName()+" Address:"+btDevice.getAddress();
Log.e("",str);
}
4.打开可可检测性:
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(intent);
注意这里的时间最多设置为300s 当大于300S时候还一样是300s
5.扫描周围的设备:
if(btAdapter.isDiscovering){
btAdapter.cancelDiscovery();
}
btAdapter.startDiscovery();//就这样启动就可以,当扫描到设备后系统会发广播,所以要注册广播来接收扫描到的设备信息
private BrodcastReceiver btReceiver = new BroadcastReceiver(){
public void onReceive(Context context,Intent intent){
String action = intent.getAction();
if(BlutoothDevice.ACTION_FOUND.equals(action)){
BluetoothDevice btDevice = intent.getParcelableExtra(
BluetoothDevice.EXTRA_DEVICE);
Log.e("",""+btDevice);
} else if(BluetoothDevice.ACTION_DISCOVERY_FINISHED.equals(action)){
Log.e("","discovery finished");
}
}
}
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
this.registerReceiver(btReceiver,filter);
filter = new IntentFilter(BluetoothDevice.ACTION_DISCOVERY_FINISHED);
this.registerReceiver(btReceiver,filter);
//别忘记在程序退出时候取消广播
public void onDestroy(){
super.onDestroy();
if(btAdapter != null){
btAdapter.cancelDiscovery;
}
this.unregisterReceiver(btReceiver);
}
6.连接,这个主要是BluetoothSocket和BluetoothServerSocket,客户端,和服务器
其实这个UUID我也是一知半解,百科看完了大概就当个ID用吧,服务端跟客户端要一样的
网上有一篇很不错的帖子讲了这部分的原理:
[url]
http://lighthearts.blog.163.com/blog/static/1726840522011791111499/
[/url]
那我就借用下他的两小块代码吧:
//服务端
private BluetoothServerSocket serverSocket = btAdapter
.listenUsingRfcommWithServiceRecord(SERVICE_NAME,SERVICE_UUID);
private BluetoothSocket exchangeSocket = serverSocket.accept();
//客户端
private BluetoothSocket clientSocket = btDevice
.createRfcommSocketToServerRecord(SERVER_UUID);
clientSocket.connet();
//接下来就是clientSocket.getOutputStream().write(byte[]);