利用藍芽來傳送圖片等檔案

aasoga發表於2017-05-25

最近在研究藍芽,藍芽裝置間傳輸訊息可以通過BluetoothAdapter的startDiscovery方法來搜尋裝置,得到device的address,然後利用反射呼叫BluetoothDevice 的createBond方法來進行配對,然後就可以得到socket然後進行連線了,比較麻煩。
在網上找到一種通過呼叫系統api用藍芽進行傳輸的方法,在這裡分享一下。

        /**
     * 通過藍芽傳送檔案
     */
    private void sendFile(Activity activity, File file) {
        PackageManager localPackageManager = activity.getPackageManager();
        Intent localIntent = null;
        HashMap<String, ActivityInfo> localHashMap = null;
        try {
            localIntent = new Intent();
            localIntent.setAction(Intent.ACTION_SEND);
//            localIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File(mPathList.get(mCurrentPosition))));
            localIntent.putExtra(Intent.EXTRA_STREAM, FileProvider.getUriForFile(getApplicationContext(), getPackageName() + ".provider", file));
            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;
                Log.e("bluetooth", "processName " + str);
                if (str.contains("bluetooth"))
                    localHashMap.put(str, localActivityInfo2);
            }
        } catch (Exception localException) {
        }
        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();
        }
        Log.e("bluetooth", "packageName" + localActivityInfo1.packageName + "name" + localActivityInfo1.name);
        if (localActivityInfo1 != null) {
            localIntent.setComponent(new ComponentName(
                    localActivityInfo1.packageName, localActivityInfo1.name));
            activity.startActivityForResult(localIntent, 4098);
            return;
        }
    }

原理就是通過ACTION_SEND這個action的intent得到所有能傳輸的系統程式,然後找出藍芽程式,通過setComponent設定intent然後跳轉過去。在6.0系統上跳轉的activity是com.android.bluetooth.opp.BluetoothOppLauncherActivity

相關文章