最近項目上需要實現藍牙傳輸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);
}
效果: