转载请注明出处:http://blog.csdn.net/vnanyesheshou/article/details/70256004
本文已授权微信公众号 fanfan程序媛 独家发布 扫一扫文章底部的二维码或在微信搜索 fanfan程序媛 即可关注
Android蓝牙功能(传统蓝牙、ble、hid)这三方面功能之前的博客都已经写了。现在接着了解蓝牙OPP传输文件相关功能。Android手机使用中,经常会用到通过蓝牙分享文件给附近的朋友。那么具体是如何实现的,大部分朋友都不是很清楚。看一下源码是如何实现该功能的。
1 BluetoothOppLauncherActivity |
Android手机点击某文件进行蓝牙分享的时候,会跳转到系统自带应用Bluetooth中。
具体文件:packages/apps/Bluetooth/src/com/android/bluetooth/opp/BluetoothOppLauncherActivity.java
看一下BluetoothOppLauncherActivity是如何处理分享文件请求的。
if (action.equals(Intent.ACTION_SEND) || action.equals(Intent.ACTION_SEND_MULTIPLE)) {
//Check if Bluetooth is available in the beginning instead of at the end
if (!isBluetoothAllowed()) {
Intent in = new Intent(this, BluetoothOppBtErrorActivity.class);
in.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
in.putExtra("title", this.getString(R.string.airplane_error_title));
in.putExtra("content", this.getString(R.string.airplane_error_msg));
startActivity(in);
finish();
return;
}
//..........下面接着说。
}
BluetoothOppLauncherActivity并没有界面(没有setContentView),只是一个中转站,它根据当前蓝牙等相关状态进行跳转。Intent.ACTION_SEND和Intent.ACTION_SEND_MULTIPLE的区别是前者表示单个文件,后者表示多个文件。这里只研究下分享单个文件,分享单个文件懂了,多个文件道理类似。
其中isBluetoothAllowed()函数会先判断飞行模式是否开启,如果没有开启则返回true。如果开启,则进行下一步判断飞行模式是否重要,如果不重要则返回true(说明蓝牙可以使用)。如果重要则继续分析飞行模式下是否可以打开蓝牙,可以打开蓝牙则返回true,否则返回false。总的来说该函数就是判断当前蓝牙是否允许使用。不允许使用蓝牙则跳转到BluetoothOppBtErrorActivity。
接着向下:
if (action.equals(Intent.ACTION_SEND)) { //单个文件
final String type = intent.getType();
final Uri stream = (Uri)intent.getParcelableExtra(Intent.EXTRA_STREAM);
CharSequence extra_text = intent.getCharSequenceExtra(Intent.EXTRA_TEXT);
if (stream != null && type != null) { //分享文件
Thread t = new Thread(new Runnable() {
public void run() {
BluetoothOppManager.getInstance(BluetoothOppLauncherActivity.this)
.saveSendingFileInfo(type,stream.toString(), false);
launchDevicePicker();
finish();
}
});
t.start();
return;
} else if (extra_text != null && type != null) { //分享text字符串,没有文件
final Uri fileUri = creatFileForSharedContent(this, extra_text); //创建文件,将内容写入文件
if (fileUri != null) {
Thread t = new Thread(new Runnable() {
public void run() {
BluetoothOppManager.getInstance(BluetoothOppLauncherActivity.this)
.saveSendingFileInfo(type,fileUri.toString(), false);
launchDevicePicker();
finish();
}
});
t.start();
return;
}
//.........
}
使用过Android系统分享的应该知道,其支持文件(图片、视频等)、字符串。而这里会对文件、字符串进行区分处理,字符串则先创建文件然后在进行分享。
launchDevicePicker()函数中先判断蓝牙是否开启。
如果蓝牙没有开启则跳转到BluetoothOppBtEnableActivity显示dialog(询问是否开启蓝牙),点击取消则则退出,点击打开则打开蓝牙并跳到BluetoothOppBtEnablingActivity(该activity主要显示一个progress dialog)。当蓝牙打开,则BluetoothOppBtEnablingActivity 界面finish。BluetoothOppReceiver广播接收者接收到蓝牙开启,跳转到DevicePickerActivity界面(系统Settings应用)。
如果蓝牙已开启,则直接跳转到跳转到DevicePickerActivity界面(系统Settings应用)。
launchDevicePicker()下的跳转代码:
//ACTION_LAUNCH="android.bluetooth.devicepicker.action.LAUNCH"
Intent in1 = new Intent(BluetoothDevice