Android 實現無網絡傳輸文件

最近的項目須要實現一個 Android 手機之間無網絡傳輸文件的功能,就發現了 **Wifi P2P(Wifi點對點)**這麼一個功能,最後也實現了經過 Wifi 隔空傳輸文件 的功能,這裏我也來整理下代碼,分享給你們。java

Wifi P2P 是在 Android 4.0 以及更高版本系統中加入的功能,經過 Wifi P2P 能夠在不鏈接網絡的狀況下,直接與配對的設備進行數據交換。相對於藍牙,Wifi P2P 的搜索速度和傳輸速度更快,傳輸距離更遠android

項目主頁:Android 實現無網絡傳輸文件 ,歡迎 stargit

實現的效果以下所示:github

通常而言,開發步驟分爲如下幾點:服務器

  1. 在 AndroidManifest 中聲明相關權限(網絡和文件讀寫權限)
  2. 獲取 WifiP2pManager ,註冊相關廣播監聽Wifi直連的狀態變化
  3. 指定某一臺設備爲服務器(用來接收文件),建立羣組並做爲羣主存在,在指定端口監聽客戶端的鏈接請求,等待客戶端發起鏈接請求以及文件傳輸請求
  4. 客戶端(用來發送文件)主動搜索附近的設備,加入到服務器建立的羣組,獲取服務器的IP地址,向其發起文件傳輸請求
  5. 校驗文件完整性

1、聲明權限

Wifi P2P 技術並不會訪問網絡,但因爲會使用到 Java Socket,因此須要申請網絡權限。此外,因爲是要實現文件互傳,因此也須要申請SD卡讀寫權限。網絡

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
    <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
複製代碼

2、註冊廣播

與 Wifi P2P 相關的廣播有如下幾個:併發

  1. WIFI_P2P_STATE_CHANGED_ACTION( 用於指示 Wifi P2P 是否可用 )
  2. WIFI_P2P_PEERS_CHANGED_ACTION( 對等節點列表發生了變化 )
  3. WIFI_P2P_CONNECTION_CHANGED_ACTION( Wifi P2P 的鏈接狀態發生了改變 )
  4. WIFI_P2P_THIS_DEVICE_CHANGED_ACTION( 本設備的設備信息發生了變化 )

當接收到這幾個廣播時,咱們都須要到 WifiP2pManager (對等網絡管理器)來進行相應的信息請求,此外還須要用到 Channel 對象做爲請求參數app

mWifiP2pManager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
mChannel = mWifiP2pManager.initialize(this, getMainLooper(), this);
複製代碼

當收到 WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION 廣播時,能夠判斷當前 Wifi P2P是否可用異步

int state = intent.getIntExtra(WifiP2pManager.EXTRA_WIFI_STATE, -1);
if (state == WifiP2pManager.WIFI_P2P_STATE_ENABLED) {
    mDirectActionListener.wifiP2pEnabled(true);
} else {
    mDirectActionListener.wifiP2pEnabled(false);                
}
複製代碼

當收到 WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION 廣播時,意味設備周圍的可用設備列表發生了變化,能夠經過 requestPeers 方法獲得可用的設備列表,以後就能夠選擇當中的某一個設備進行鏈接操做socket

mWifiP2pManager.requestPeers(mChannel, new WifiP2pManager.PeerListListener() {
    @Override
    public void onPeersAvailable(WifiP2pDeviceList peers) {
        mDirectActionListener.onPeersAvailable(peers.getDeviceList());
    }
});
複製代碼

當收到 WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION 廣播時,意味着 Wifi P2P 的鏈接狀態發生了變化,多是鏈接到了某設備,或者是與某設備斷開了鏈接

NetworkInfo networkInfo = intent.getParcelableExtra(WifiP2pManager.EXTRA_NETWORK_INFO);
if (networkInfo.isConnected()) {
    mWifiP2pManager.requestConnectionInfo(mChannel, new WifiP2pManager.ConnectionInfoListener() {
        @Override
        public void onConnectionInfoAvailable(WifiP2pInfo info) {
            mDirectActionListener.onConnectionInfoAvailable(info);
        }
    });
    Log.e(TAG, "已鏈接p2p設備");
} else {
    mDirectActionListener.onDisconnection();
    Log.e(TAG, "與p2p設備已斷開鏈接");
}
複製代碼

若是是與某設備鏈接上了,則能夠經過 requestConnectionInfo 方法獲取到鏈接信息

當收到 WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION 廣播時,則能夠獲取到本設備變化後的設備信息

(WifiP2pDevice) intent.getParcelableExtra(WifiP2pManager.EXTRA_WIFI_P2P_DEVICE)
複製代碼

能夠看出 Wifi P2P 的接口高度異步化,到如今已經用到了三個系統的回調函數,一個用於 WifiP2pManager 的初始化,兩個用於在廣播中異步請求數據,爲了簡化操做,此處統一使用一個自定義的回調函數,方法含義與系統的回調函數一致

public interface DirectActionListener extends WifiP2pManager.ChannelListener {

    void wifiP2pEnabled(boolean enabled);

    void onConnectionInfoAvailable(WifiP2pInfo wifiP2pInfo);

    void onDisconnection();

    void onSelfDeviceAvailable(WifiP2pDevice wifiP2pDevice);

    void onPeersAvailable(Collection<WifiP2pDevice> wifiP2pDeviceList);

}
複製代碼

因此,整個廣播接收器使用到的全部代碼是:

/** * 做者:leavesC * 時間:2019/2/27 23:58 * 描述: * GitHub:https://github.com/leavesC * Blog:https://www.jianshu.com/u/9df45b87cfdf */
public class DirectBroadcastReceiver extends BroadcastReceiver {

    private static final String TAG = "DirectBroadcastReceiver";

    private WifiP2pManager mWifiP2pManager;

    private WifiP2pManager.Channel mChannel;

    private DirectActionListener mDirectActionListener;

    public DirectBroadcastReceiver(WifiP2pManager wifiP2pManager, WifiP2pManager.Channel channel, DirectActionListener directActionListener) {
        mWifiP2pManager = wifiP2pManager;
        mChannel = channel;
        mDirectActionListener = directActionListener;
    }

    public static IntentFilter getIntentFilter() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
        intentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
        intentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
        intentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);
        return intentFilter;
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.e(TAG, "接收到廣播: " + intent.getAction());
        if (!TextUtils.isEmpty(intent.getAction())) {
            switch (intent.getAction()) {
                // 用於指示 Wifi P2P 是否可用
                case WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION: {
                    int state = intent.getIntExtra(WifiP2pManager.EXTRA_WIFI_STATE, -1);
                    if (state == WifiP2pManager.WIFI_P2P_STATE_ENABLED) {
                        mDirectActionListener.wifiP2pEnabled(true);
                    } else {
                        mDirectActionListener.wifiP2pEnabled(false);
                        List<WifiP2pDevice> wifiP2pDeviceList = new ArrayList<>();
                        mDirectActionListener.onPeersAvailable(wifiP2pDeviceList);
                    }
                    break;
                }
                // 對等節點列表發生了變化
                case WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION: {
                    mWifiP2pManager.requestPeers(mChannel, new WifiP2pManager.PeerListListener() {
                        @Override
                        public void onPeersAvailable(WifiP2pDeviceList peers) {
                            mDirectActionListener.onPeersAvailable(peers.getDeviceList());
                        }
                    });
                    break;
                }
                // Wifi P2P 的鏈接狀態發生了改變
                case WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION: {
                    NetworkInfo networkInfo = intent.getParcelableExtra(WifiP2pManager.EXTRA_NETWORK_INFO);
                    if (networkInfo.isConnected()) {
                        mWifiP2pManager.requestConnectionInfo(mChannel, new WifiP2pManager.ConnectionInfoListener() {
                            @Override
                            public void onConnectionInfoAvailable(WifiP2pInfo info) {
                                mDirectActionListener.onConnectionInfoAvailable(info);
                            }
                        });
                        Log.e(TAG, "已鏈接p2p設備");
                    } else {
                        mDirectActionListener.onDisconnection();
                        Log.e(TAG, "與p2p設備已斷開鏈接");
                    }
                    break;
                }
                //本設備的設備信息發生了變化
                case WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION: {
                    mDirectActionListener.onSelfDeviceAvailable((WifiP2pDevice) intent.getParcelableExtra(WifiP2pManager.EXTRA_WIFI_P2P_DEVICE));
                    break;
                }
            }
        }
    }

}
複製代碼

3、服務器端建立羣組

假設當設備A搜索到了設備B,並與設備B鏈接到了一塊兒,此時系統會自動建立一個羣組(Group)並隨機指定一臺設備爲羣主(GroupOwner)。此時,對於兩臺設備來講,羣主的IP地址是可知的(系統回調函數中有提供),但客戶端的IP地址須要再來經過其餘方法來主動獲取。例如,能夠在設備鏈接成功後,客戶端主動發起對服務器端的Socket鏈接請求,服務器端在指定端口監聽客戶端的鏈接請求,當鏈接成功後,服務器端就能夠獲取到客戶端的IP地址了 此處爲了簡化操做,直接指定某臺設備做爲服務器端(羣主),即直接指定某臺設備用來接收文件

所以,服務器端要主動建立羣組,並等待客戶端的鏈接

wifiP2pManager.createGroup(channel, new WifiP2pManager.ActionListener() {
    @Override
    public void onSuccess() {
        Log.e(TAG, "createGroup onSuccess");
        dismissLoadingDialog();
        showToast("onSuccess");
    }

     @Override
     public void onFailure(int reason) {
        Log.e(TAG, "createGroup onFailure: " + reason);
        dismissLoadingDialog();
        showToast("onFailure");
    }
});
複製代碼

此處,使用 IntentService 在後臺監聽客戶端的 Socket 鏈接請求,並經過輸入輸出流來傳輸文件。此處的代碼比較簡單,就只是在指定端口一直堵塞監聽客戶端的鏈接請求,獲取待傳輸的文件信息模型 FileTransfer ,以後就進行實際的數據傳輸

@Override
    protected void onHandleIntent(Intent intent) {
        clean();
        File file = null;
        try {
            serverSocket = new ServerSocket();
            serverSocket.setReuseAddress(true);
            serverSocket.bind(new InetSocketAddress(PORT));
            Socket client = serverSocket.accept();
            Log.e(TAG, "客戶端IP地址 : " + client.getInetAddress().getHostAddress());
            inputStream = client.getInputStream();
            objectInputStream = new ObjectInputStream(inputStream);
            FileTransfer fileTransfer = (FileTransfer) objectInputStream.readObject();
            Log.e(TAG, "待接收的文件: " + fileTransfer);
            String name = new File(fileTransfer.getFilePath()).getName();
            //將文件存儲至指定位置
            file = new File(Environment.getExternalStorageDirectory() + "/" + name);
            fileOutputStream = new FileOutputStream(file);
            byte buf[] = new byte[512];
            int len;
            long total = 0;
            int progress;
            while ((len = inputStream.read(buf)) != -1) {
                fileOutputStream.write(buf, 0, len);
                total += len;
                progress = (int) ((total * 100) / fileTransfer.getFileLength());
                Log.e(TAG, "文件接收進度: " + progress);
                if (progressChangListener != null) {
                    progressChangListener.onProgressChanged(fileTransfer, progress);
                }
            }
            serverSocket.close();
            inputStream.close();
            objectInputStream.close();
            fileOutputStream.close();
            serverSocket = null;
            inputStream = null;
            objectInputStream = null;
            fileOutputStream = null;
            Log.e(TAG, "文件接收成功,文件的MD5碼是:" + Md5Util.getMd5(file));
        } catch (Exception e) {
            Log.e(TAG, "文件接收 Exception: " + e.getMessage());
        } finally {
            clean();
            if (progressChangListener != null) {
                progressChangListener.onTransferFinished(file);
            }
            //再次啓動服務,等待客戶端下次鏈接
            startService(new Intent(this, WifiServerService.class));
        }
    }
複製代碼

由於客戶端可能會屢次發起鏈接請求,因此當此處文件傳輸完成後(無論成功或失敗),都須要從新 startService ,讓服務再次堵塞等待客戶端的鏈接請求

FileTransfer 包含三個字段,MD5碼值用於校驗文件的完整性,fileLength 是爲了用於計算文件的傳輸進度

public class FileTransfer implements Serializable {

    //文件路徑
    private String filePath;

    //文件大小
    private long fileLength;

    //MD5碼
    private String md5;

    ···
    
}
複製代碼

爲了將文件傳輸進度發佈到外部界面,因此除了須要啓動Service外,界面還須要綁定Service,此處就須要用到一個更新文件傳輸狀態的接口

public interface OnProgressChangListener {

        //當傳輸進度發生變化時
        void onProgressChanged(FileTransfer fileTransfer, int progress);

        //當傳輸結束時
        void onTransferFinished(File file);

    }
複製代碼

所以,須要將 progressChangListener 做爲參數傳給 WifiServerService ,並在進度變化時更新進度對話框

private WifiServerService.OnProgressChangListener progressChangListener = new WifiServerService.OnProgressChangListener() {
        @Override
        public void onProgressChanged(final FileTransfer fileTransfer, final int progress) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    progressDialog.setMessage("文件名: " + new File(fileTransfer.getFilePath()).getName());
                    progressDialog.setProgress(progress);
                    progressDialog.show();
                }
            });
        }

        @Override
        public void onTransferFinished(final File file) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    progressDialog.cancel();
                    if (file != null && file.exists()) {
                        openFile(file.getPath());
                    }
                }
            });
        }
    };
複製代碼

4、客戶端加入羣組併發起文件傳輸請求

文件發送界面 SendFileActivity 須要實現 DirectActionListener 接口 首先,須要先註冊P2P廣播,以便獲取周邊設備信息以及鏈接狀態

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_send_file);
        initView();
        mWifiP2pManager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
        mChannel = mWifiP2pManager.initialize(this, getMainLooper(), this);
        broadcastReceiver = new DirectBroadcastReceiver(mWifiP2pManager, mChannel, this);
        registerReceiver(broadcastReceiver, DirectBroadcastReceiver.getIntentFilter());
    }
複製代碼

經過 discoverPeers 方法搜索周邊設備,回調函數用於通知方法是否調用成功

mWifiP2pManager.discoverPeers(mChannel, new WifiP2pManager.ActionListener() {
    @Override
    public void onSuccess() {
        showToast("Success");
    }

    @Override
    public void onFailure(int reasonCode) {
        showToast("Failure");
        loadingDialog.cancel();
     }
});
複製代碼

當搜索結束後,系統就會觸發 WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION 廣播,此時就能夠調用 requestPeers 方法獲取設備列表信息,此處用 RecyclerView 展現列表,在 onPeersAvailable 方法刷新列表

mWifiP2pManager.requestPeers(mChannel, new WifiP2pManager.PeerListListener() {
    @Override
    public void onPeersAvailable(WifiP2pDeviceList peers) {
        mDirectActionListener.onPeersAvailable(peers.getDeviceList());
    }
});
複製代碼
@Override
    public void onPeersAvailable(Collection<WifiP2pDevice> wifiP2pDeviceList) {
        Log.e(TAG, "onPeersAvailable :" + wifiP2pDeviceList.size());
        this.wifiP2pDeviceList.clear();
        this.wifiP2pDeviceList.addAll(wifiP2pDeviceList);
        deviceAdapter.notifyDataSetChanged();
        loadingDialog.cancel();
    }
複製代碼

以後,經過點擊事件選中羣主(服務器端)設備,經過 connect 方法請求與之進行鏈接

private void connect() {
    WifiP2pConfig config = new WifiP2pConfig();
    if (config.deviceAddress != null && mWifiP2pDevice != null) {
        config.deviceAddress = mWifiP2pDevice.deviceAddress;
        config.wps.setup = WpsInfo.PBC;
        showLoadingDialog("正在鏈接 " + mWifiP2pDevice.deviceName);
        mWifiP2pManager.connect(mChannel, config, new WifiP2pManager.ActionListener() {
            @Override
            public void onSuccess() {
                Log.e(TAG, "connect onSuccess");
            }

            @Override
            public void onFailure(int reason) {
                showToast("鏈接失敗 " + reason);
                dismissLoadingDialog();
            }
        });
    }
}
複製代碼

此處依然沒法經過函數函數來判斷鏈接結果,須要依靠系統發出的 WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION 方法來獲取到鏈接結果,在此處能夠經過 requestConnectionInfo 獲取到組鏈接信息,信息最後經過 onConnectionInfoAvailable 方法傳遞出來,在此能夠判斷當前設備是否爲羣主,獲取羣組IP地址

@Override
public void onConnectionInfoAvailable(WifiP2pInfo wifiP2pInfo) {
    dismissLoadingDialog();
    wifiP2pDeviceList.clear();
    deviceAdapter.notifyDataSetChanged();
    btn_disconnect.setEnabled(true);
    btn_chooseFile.setEnabled(true);
    Log.e(TAG, "onConnectionInfoAvailable");
    Log.e(TAG, "onConnectionInfoAvailable groupFormed: " + wifiP2pInfo.groupFormed);
    Log.e(TAG, "onConnectionInfoAvailable isGroupOwner: " + wifiP2pInfo.isGroupOwner);
    Log.e(TAG, "onConnectionInfoAvailable getHostAddress: " + wifiP2pInfo.groupOwnerAddress.getHostAddress());
    StringBuilder stringBuilder = new StringBuilder();
    if (mWifiP2pDevice != null) {
        stringBuilder.append("鏈接的設備名:");
        stringBuilder.append(mWifiP2pDevice.deviceName);
        stringBuilder.append("\n");
        stringBuilder.append("鏈接的設備的地址:");
        stringBuilder.append(mWifiP2pDevice.deviceAddress);
    }
    stringBuilder.append("\n");
    stringBuilder.append("是否羣主:");
    stringBuilder.append(wifiP2pInfo.isGroupOwner ? "是羣主" : "非羣主");
    stringBuilder.append("\n");
    stringBuilder.append("羣主IP地址:");
    stringBuilder.append(wifiP2pInfo.groupOwnerAddress.getHostAddress());
    tv_status.setText(stringBuilder);
    if (wifiP2pInfo.groupFormed && !wifiP2pInfo.isGroupOwner) {
        this.wifiP2pInfo = wifiP2pInfo;
    }
}
複製代碼

至此服務器端和客戶端已經經過 Wifi P2P 鏈接在了一塊兒,客戶端也獲取到了服務器端的IP地址,在選取好待發送的文件後就能夠主動發起對服務器端的鏈接請求了 發起選取文件的方法

Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
intent.addCategory(Intent.CATEGORY_OPENABLE);
startActivityForResult(intent, 1);
複製代碼

獲取選取的文件的實際路徑

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == 1) {
        if (resultCode == RESULT_OK) {
            Uri uri = data.getData();
            if (uri != null) {
                String path = getPath(this, uri);
                if (path != null) {
                    File file = new File(path);
                    if (file.exists() && wifiP2pInfo != null) {
                        FileTransfer fileTransfer = new FileTransfer(file.getPath(), file.length());
                        Log.e(TAG, "待發送的文件:" + fileTransfer);
                        new WifiClientTask(this, fileTransfer).execute(wifiP2pInfo.groupOwnerAddress.getHostAddress());
                    }
                }
            }
        }
    }
}

private String getPath(Context context, Uri uri) {
    if ("content".equalsIgnoreCase(uri.getScheme())) {
        Cursor cursor = context.getContentResolver().query(uri, new String[]{"_data"}, null, null, null);
        if (cursor != null) {
           if (cursor.moveToFirst()) {
                String data = cursor.getString(cursor.getColumnIndex("_data"));
                cursor.close();
                return data;
            }
        }
    } else if ("file".equalsIgnoreCase(uri.getScheme())) {
        return uri.getPath();
    }
    return null;
}
複製代碼

文件的發送操做放到 AsyncTask 中處理,將服務器端的IP地址做爲參數傳進來,在正式發送文件前,先發送包含文件信息(文件名,文件大小,文件MD5碼)的信息模型 FileTransfer ,並在發送文件的過程當中同時更新進度

/** * 做者:leavesC * 時間:2019/2/27 23:56 * 描述:客戶端發送文件 * GitHub:https://github.com/leavesC * Blog:https://www.jianshu.com/u/9df45b87cfdf */
public class WifiClientTask extends AsyncTask<String, Integer, Boolean> {

    private ProgressDialog progressDialog;

    private FileTransfer fileTransfer;

    private static final int PORT = 4786;

    private static final String TAG = "WifiClientTask";

    public WifiClientTask(Context context, FileTransfer fileTransfer) {
        this.fileTransfer = fileTransfer;
        progressDialog = new ProgressDialog(context);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.setCancelable(false);
        progressDialog.setCanceledOnTouchOutside(false);
        progressDialog.setTitle("正在發送文件");
        progressDialog.setMax(100);
    }

    @Override
    protected void onPreExecute() {
        progressDialog.show();
    }

    @Override
    protected Boolean doInBackground(String... strings) {
        fileTransfer.setMd5(Md5Util.getMd5(new File(fileTransfer.getFilePath())));
        Log.e(TAG, "文件的MD5碼值是:" + fileTransfer.getMd5());
        Socket socket = null;
        OutputStream outputStream = null;
        ObjectOutputStream objectOutputStream = null;
        InputStream inputStream = null;
        try {
            socket = new Socket();
            socket.bind(null);
            socket.connect((new InetSocketAddress(strings[0], PORT)), 10000);
            outputStream = socket.getOutputStream();
            objectOutputStream = new ObjectOutputStream(outputStream);
            objectOutputStream.writeObject(fileTransfer);
            inputStream = new FileInputStream(new File(fileTransfer.getFilePath()));
            long fileSize = fileTransfer.getFileLength();
            long total = 0;
            byte buf[] = new byte[512];
            int len;
            while ((len = inputStream.read(buf)) != -1) {
                outputStream.write(buf, 0, len);
                total += len;
                int progress = (int) ((total * 100) / fileSize);
                publishProgress(progress);
                Log.e(TAG, "文件發送進度:" + progress);
            }
            outputStream.close();
            objectOutputStream.close();
            inputStream.close();
            socket.close();
            outputStream = null;
            objectOutputStream = null;
            inputStream = null;
            socket = null;
            Log.e(TAG, "文件發送成功");
            return true;
        } catch (Exception e) {
            Log.e(TAG, "文件發送異常 Exception: " + e.getMessage());
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (objectOutputStream != null) {
                try {
                    objectOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (socket != null) {
                try {
                    socket.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return false;
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        progressDialog.setProgress(values[0]);
    }

    @Override
    protected void onPostExecute(Boolean aBoolean) {
        progressDialog.cancel();
        Log.e(TAG, "onPostExecute: " + aBoolean);
    }

}
複製代碼

5、校驗文件完整性

傳輸文件的完整性主要是經過計算文件的MD5碼值來保證了,在發送文件前,即在 WifiClientTask 的 doInBackground 方法中進行計算,將MD5碼值賦給 FileTransfer 模型,經過以下方法計算獲得

/** * 做者:leavesC * 時間:2019/2/27 23:57 * 描述: * GitHub:https://github.com/leavesC * Blog:https://www.jianshu.com/u/9df45b87cfdf */
public class Md5Util {

    public static String getMd5(File file) {
        InputStream inputStream = null;
        byte[] buffer = new byte[2048];
        int numRead;
        MessageDigest md5;
        try {
            inputStream = new FileInputStream(file);
            md5 = MessageDigest.getInstance("MD5");
            while ((numRead = inputStream.read(buffer)) > 0) {
                md5.update(buffer, 0, numRead);
            }
            inputStream.close();
            inputStream = null;
            return md5ToString(md5.digest());
        } catch (Exception e) {
            return null;
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private static String md5ToString(byte[] md5Bytes) {
        StringBuilder hexValue = new StringBuilder();
        for (byte b : md5Bytes) {
            int val = ((int) b) & 0xff;
            if (val < 16) {
                hexValue.append("0");
            }
            hexValue.append(Integer.toHexString(val));
        }
        return hexValue.toString();
    }

}
複製代碼

由於客戶端會將 FileTransfer 傳給服務器端,因此服務器端在文件傳輸結束後,能夠從新計算文件的 MD5碼值,進行對比以判斷文件是否完整

項目主頁:Android 實現無網絡傳輸文件 ,歡迎 star

相關文章
相關標籤/搜索