最近項目上須要實現藍牙傳輸apk的一個功能,可以搜索周圍的藍牙手機並分享文件。從需求上講android手機自帶的藍牙傳輸模塊就能夠知足須要了,實現也很簡單。不過讓人頭疼的是,雖說通常的主流機型都配置有藍牙模塊,可是android機型碎片化太嚴重,不一樣android版本手機藍牙功能也不同。4.0.3如下版本和以上版本使用的藍牙包是不一樣的,分別是"com.android.bluetooth"和"com.mediatek.bluetooth"。還有一些廠商對藍牙模塊進行的定製修改,好比華爲的c8812。另外,android藍牙功能是api5以上纔有的,因此android的minSdkVersion要不低於5才行。android
網上不少android調用藍牙發送模塊的例子,完整而且可以兼容多系統的例子不多,這裏發一個我用在項目中的例子。api
/** * 經過藍牙發送文件 */ 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); }
效果:app