android实现蓝牙文件发送的实例代码,支持多种机型
最近项目上需要实现蓝牙传输apk的一个功能,能够搜索周围的蓝牙手机并分享文件。从需求上讲android手机自带的蓝牙传输模块就可以满足需要了,实现也很简单。不过让人头疼的是,虽然说一般的主流机型都配置有蓝牙模块,但是android机型碎片化太严重,不同android版本手机蓝牙功能也不一样。4.0.3以下版本和以上版本使用的蓝牙包是不同的,分别是"com.android.bluetooth"和"com.mediatek.bluetooth"。还有一些厂商对蓝牙模块进行的定制修改,比如华为的c8812。另外,android蓝牙功能是api5以上才有的,所以android的minsdkversion要不低于5才行。
网上很多android调用蓝牙发送模块的例子,完整并且能够兼容多系统的例子很少,这里发一个我用在项目中的例子。
/**
* 通过蓝牙发送文件
*/
private void sendfile(activity activity) {
packagemanager localpackagemanager = activity.getpackagemanager();
intent localintent = null;
hashmap<string, activityinfo> localhashmap = null;
try {
localintent = new intent();
localintent.setaction(intent.action_send);
file file = new file(taexternaloverfroyoutils.getdiskcachedir(this,
constants.download_dir).getabsolutepath(),
textutils.genapkname(worm.getwormid()));
localintent.putextra(intent.extra_stream, uri.fromfile(file));
// localintent.putextra(intent.extra_stream,
// uri.fromfile(new file(localapplicationinfo.sourcedir)));
localintent.settype("*/*");
list<resolveinfo> locallist = localpackagemanager.queryintentactivities(
localintent, 0);
localhashmap = new hashmap<string, activityinfo>();
iterator<resolveinfo> localiterator1 = locallist.iterator();
while (localiterator1.hasnext()) {
resolveinfo resolveinfo = (resolveinfo) localiterator1.next();
activityinfo localactivityinfo2 = resolveinfo.activityinfo;
string str = localactivityinfo2.applicationinfo.processname;
if (str.contains("bluetooth"))
localhashmap.put(str, localactivityinfo2);
}
} catch (exception localexception) {
toasthelper.showbluetoothsupporterr(activity);
}
if (localhashmap.size() == 0)
toasthelper.showbluetoothsupporterr(activity);
activityinfo localactivityinfo1 = (activityinfo) localhashmap
.get("com.android.bluetooth");
if (localactivityinfo1 == null) {
localactivityinfo1 = (activityinfo) localhashmap
.get("com.mediatek.bluetooth");
}
if (localactivityinfo1 == null) {
iterator<activityinfo> localiterator2 = localhashmap.values().iterator();
if (localiterator2.hasnext())
localactivityinfo1 = (activityinfo) localiterator2.next();
}
if (localactivityinfo1 != null) {
localintent.setcomponent(new componentname(
localactivityinfo1.packagename, localactivityinfo1.name));
activity.startactivityforresult(localintent, 4098);
return;
}
toasthelper.showbluetoothsupporterr(activity);
}
效果: