最近的項(xiàng)目需要實(shí)現(xiàn)一個(gè) Android 手機(jī)之間無(wú)網(wǎng)絡(luò)傳輸文件的功能勒虾,就發(fā)現(xiàn)了 Wifi P2P(Wifi點(diǎn)對(duì)點(diǎn))這么一個(gè)功能缠劝,最后也實(shí)現(xiàn)了通過(guò) Wifi 隔空傳輸文件 的功能雷则,這里我也來(lái)整理下代碼,分享給大家盹憎。
Wifi P2P 是在 Android 4.0 以及更高版本系統(tǒng)中加入的功能拒贱,通過(guò) Wifi P2P 可以在不連接網(wǎng)絡(luò)的情況下,直接與配對(duì)的設(shè)備進(jìn)行數(shù)據(jù)交換崔梗。相對(duì)于藍(lán)牙夜只,Wifi P2P 的搜索速度和傳輸速度更快,傳輸距離更遠(yuǎn)
項(xiàng)目主頁(yè):Android 實(shí)現(xiàn)無(wú)網(wǎng)絡(luò)傳輸文件 蒜魄,歡迎 star
實(shí)現(xiàn)的效果如下所示:
一般而言扔亥,開(kāi)發(fā)步驟分為以下幾點(diǎn):
- 在 AndroidManifest 中聲明相關(guān)權(quán)限(網(wǎng)絡(luò)和文件讀寫(xiě)權(quán)限)
- 獲取 WifiP2pManager 场躯,注冊(cè)相關(guān)廣播監(jiān)聽(tīng)Wifi直連的狀態(tài)變化
- 指定某一臺(tái)設(shè)備為服務(wù)器(用來(lái)接收文件),創(chuàng)建群組并作為群主存在旅挤,在指定端口監(jiān)聽(tīng)客戶端的連接請(qǐng)求踢关,等待客戶端發(fā)起連接請(qǐng)求以及文件傳輸請(qǐng)求
- 客戶端(用來(lái)發(fā)送文件)主動(dòng)搜索附近的設(shè)備,加入到服務(wù)器創(chuàng)建的群組粘茄,獲取服務(wù)器的IP地址签舞,向其發(fā)起文件傳輸請(qǐng)求
- 校驗(yàn)文件完整性
一、聲明權(quán)限
Wifi P2P 技術(shù)并不會(huì)訪問(wèn)網(wǎng)絡(luò)柒瓣,但由于會(huì)使用到 Java Socket儒搭,所以需要申請(qǐng)網(wǎng)絡(luò)權(quán)限。此外嘹朗,由于是要實(shí)現(xiàn)文件互傳师妙,所以也需要申請(qǐng)SD卡讀寫(xiě)權(quán)限。
<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" />
二屹培、注冊(cè)廣播
與 Wifi P2P 相關(guān)的廣播有以下幾個(gè):
- WIFI_P2P_STATE_CHANGED_ACTION( 用于指示 Wifi P2P 是否可用 )
- WIFI_P2P_PEERS_CHANGED_ACTION( 對(duì)等節(jié)點(diǎn)列表發(fā)生了變化 )
- WIFI_P2P_CONNECTION_CHANGED_ACTION( Wifi P2P 的連接狀態(tài)發(fā)生了改變 )
- WIFI_P2P_THIS_DEVICE_CHANGED_ACTION( 本設(shè)備的設(shè)備信息發(fā)生了變化 )
當(dāng)接收到這幾個(gè)廣播時(shí)默穴,我們都需要到 WifiP2pManager (對(duì)等網(wǎng)絡(luò)管理器)來(lái)進(jìn)行相應(yīng)的信息請(qǐng)求,此外還需要用到 Channel 對(duì)象作為請(qǐng)求參數(shù)
mWifiP2pManager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
mChannel = mWifiP2pManager.initialize(this, getMainLooper(), this);
當(dāng)收到 WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION 廣播時(shí)褪秀,可以判斷當(dāng)前 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);
}
當(dāng)收到 WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION 廣播時(shí)蓄诽,意味設(shè)備周圍的可用設(shè)備列表發(fā)生了變化,可以通過(guò) requestPeers 方法得到可用的設(shè)備列表媒吗,之后就可以選擇當(dāng)中的某一個(gè)設(shè)備進(jìn)行連接操作
mWifiP2pManager.requestPeers(mChannel, new WifiP2pManager.PeerListListener() {
@Override
public void onPeersAvailable(WifiP2pDeviceList peers) {
mDirectActionListener.onPeersAvailable(peers.getDeviceList());
}
});
當(dāng)收到 WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION 廣播時(shí)仑氛,意味著 Wifi P2P 的連接狀態(tài)發(fā)生了變化,可能是連接到了某設(shè)備闸英,或者是與某設(shè)備斷開(kāi)了連接
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設(shè)備");
} else {
mDirectActionListener.onDisconnection();
Log.e(TAG, "與p2p設(shè)備已斷開(kāi)連接");
}
如果是與某設(shè)備連接上了锯岖,則可以通過(guò) requestConnectionInfo 方法獲取到連接信息
當(dāng)收到 WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION 廣播時(shí),則可以獲取到本設(shè)備變化后的設(shè)備信息
(WifiP2pDevice) intent.getParcelableExtra(WifiP2pManager.EXTRA_WIFI_P2P_DEVICE)
可以看出 Wifi P2P 的接口高度異步化甫何,到現(xiàn)在已經(jīng)用到了三個(gè)系統(tǒng)的回調(diào)函數(shù)出吹,一個(gè)用于 WifiP2pManager 的初始化,兩個(gè)用于在廣播中異步請(qǐng)求數(shù)據(jù)辙喂,為了簡(jiǎn)化操作捶牢,此處統(tǒng)一使用一個(gè)自定義的回調(diào)函數(shù),方法含義與系統(tǒng)的回調(diào)函數(shù)一致
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);
}
所以巍耗,整個(gè)廣播接收器使用到的所有代碼是:
/**
* 作者:leavesC
* 時(shí)間:2019/2/27 23:58
* 描述:
* GitHub:https://github.com/leavesC
* Blog:http://www.reibang.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;
}
// 對(duì)等節(jié)點(diǎn)列表發(fā)生了變化
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 的連接狀態(tài)發(fā)生了改變
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設(shè)備");
} else {
mDirectActionListener.onDisconnection();
Log.e(TAG, "與p2p設(shè)備已斷開(kāi)連接");
}
break;
}
//本設(shè)備的設(shè)備信息發(fā)生了變化
case WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION: {
mDirectActionListener.onSelfDeviceAvailable((WifiP2pDevice) intent.getParcelableExtra(WifiP2pManager.EXTRA_WIFI_P2P_DEVICE));
break;
}
}
}
}
}
三秋麸、服務(wù)器端創(chuàng)建群組
假設(shè)當(dāng)設(shè)備A搜索到了設(shè)備B,并與設(shè)備B連接到了一起炬太,此時(shí)系統(tǒng)會(huì)自動(dòng)創(chuàng)建一個(gè)群組(Group)并隨機(jī)指定一臺(tái)設(shè)備為群主(GroupOwner)灸蟆。此時(shí),對(duì)于兩臺(tái)設(shè)備來(lái)說(shuō)亲族,群主的IP地址是可知的(系統(tǒng)回調(diào)函數(shù)中有提供)次乓,但客戶端的IP地址需要再來(lái)通過(guò)其他方法來(lái)主動(dòng)獲取吓歇。例如,可以在設(shè)備連接成功后票腰,客戶端主動(dòng)發(fā)起對(duì)服務(wù)器端的Socket連接請(qǐng)求城看,服務(wù)器端在指定端口監(jiān)聽(tīng)客戶端的連接請(qǐng)求,當(dāng)連接成功后杏慰,服務(wù)器端就可以獲取到客戶端的IP地址了
此處為了簡(jiǎn)化操作测柠,直接指定某臺(tái)設(shè)備作為服務(wù)器端(群主),即直接指定某臺(tái)設(shè)備用來(lái)接收文件
因此缘滥,服務(wù)器端要主動(dòng)創(chuàng)建群組轰胁,并等待客戶端的連接
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 在后臺(tái)監(jiān)聽(tīng)客戶端的 Socket 連接請(qǐng)求朝扼,并通過(guò)輸入輸出流來(lái)傳輸文件赃阀。此處的代碼比較簡(jiǎn)單,就只是在指定端口一直堵塞監(jiān)聽(tīng)客戶端的連接請(qǐng)求擎颖,獲取待傳輸?shù)奈募畔⒛P?FileTransfer 榛斯,之后就進(jìn)行實(shí)際的數(shù)據(jù)傳輸
@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();
//將文件存儲(chǔ)至指定位置
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, "文件接收進(jìn)度: " + 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);
}
//再次啟動(dòng)服務(wù)搂捧,等待客戶端下次連接
startService(new Intent(this, WifiServerService.class));
}
}
因?yàn)榭蛻舳丝赡軙?huì)多次發(fā)起連接請(qǐng)求驮俗,所以當(dāng)此處文件傳輸完成后(不管成功或失敗)允跑,都需要重新 startService 王凑,讓服務(wù)再次堵塞等待客戶端的連接請(qǐng)求
FileTransfer 包含三個(gè)字段,MD5碼值用于校驗(yàn)文件的完整性聋丝,fileLength 是為了用于計(jì)算文件的傳輸進(jìn)度
public class FileTransfer implements Serializable {
//文件路徑
private String filePath;
//文件大小
private long fileLength;
//MD5碼
private String md5;
···
}
為了將文件傳輸進(jìn)度發(fā)布到外部界面索烹,所以除了需要啟動(dòng)Service外,界面還需要綁定Service弱睦,此處就需要用到一個(gè)更新文件傳輸狀態(tài)的接口
public interface OnProgressChangListener {
//當(dāng)傳輸進(jìn)度發(fā)生變化時(shí)
void onProgressChanged(FileTransfer fileTransfer, int progress);
//當(dāng)傳輸結(jié)束時(shí)
void onTransferFinished(File file);
}
因此百姓,需要將 progressChangListener 作為參數(shù)傳給 WifiServerService ,并在進(jìn)度變化時(shí)更新進(jìn)度對(duì)話框
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());
}
}
});
}
};
四每篷、客戶端加入群組并發(fā)起文件傳輸請(qǐng)求
文件發(fā)送界面 SendFileActivity 需要實(shí)現(xiàn) DirectActionListener 接口
首先瓣戚,需要先注冊(cè)P2P廣播端圈,以便獲取周邊設(shè)備信息以及連接狀態(tài)
@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());
}
通過(guò) discoverPeers 方法搜索周邊設(shè)備焦读,回調(diào)函數(shù)用于通知方法是否調(diào)用成功
mWifiP2pManager.discoverPeers(mChannel, new WifiP2pManager.ActionListener() {
@Override
public void onSuccess() {
showToast("Success");
}
@Override
public void onFailure(int reasonCode) {
showToast("Failure");
loadingDialog.cancel();
}
});
當(dāng)搜索結(jié)束后,系統(tǒng)就會(huì)觸發(fā) WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION 廣播舱权,此時(shí)就可以調(diào)用 requestPeers 方法獲取設(shè)備列表信息矗晃,此處用 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();
}
之后宴倍,通過(guò)點(diǎn)擊事件選中群主(服務(wù)器端)設(shè)備张症,通過(guò) connect 方法請(qǐng)求與之進(jìn)行連接
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();
}
});
}
}
此處依然無(wú)法通過(guò)函數(shù)函數(shù)來(lái)判斷連接結(jié)果仓技,需要依靠系統(tǒng)發(fā)出的 WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION 方法來(lái)獲取到連接結(jié)果,在此處可以通過(guò) requestConnectionInfo 獲取到組連接信息俗他,信息最后通過(guò) onConnectionInfoAvailable 方法傳遞出來(lái)脖捻,在此可以判斷當(dāng)前設(shè)備是否為群主,獲取群組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("連接的設(shè)備名:");
stringBuilder.append(mWifiP2pDevice.deviceName);
stringBuilder.append("\n");
stringBuilder.append("連接的設(shè)備的地址:");
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;
}
}
至此服務(wù)器端和客戶端已經(jīng)通過(guò) Wifi P2P 連接在了一起兆衅,客戶端也獲取到了服務(wù)器端的IP地址地沮,在選取好待發(fā)送的文件后就可以主動(dòng)發(fā)起對(duì)服務(wù)器端的連接請(qǐng)求了
發(fā)起選取文件的方法
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
intent.addCategory(Intent.CATEGORY_OPENABLE);
startActivityForResult(intent, 1);
獲取選取的文件的實(shí)際路徑
@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, "待發(fā)送的文件:" + 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;
}
文件的發(fā)送操作放到 AsyncTask 中處理,將服務(wù)器端的IP地址作為參數(shù)傳進(jìn)來(lái)羡亩,在正式發(fā)送文件前摩疑,先發(fā)送包含文件信息(文件名,文件大小畏铆,文件MD5碼)的信息模型 FileTransfer 雷袋,并在發(fā)送文件的過(guò)程中同時(shí)更新進(jìn)度
/**
* 作者:leavesC
* 時(shí)間:2019/2/27 23:56
* 描述:客戶端發(fā)送文件
* GitHub:https://github.com/leavesC
* Blog:http://www.reibang.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("正在發(fā)送文件");
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, "文件發(fā)送進(jìn)度:" + progress);
}
outputStream.close();
objectOutputStream.close();
inputStream.close();
socket.close();
outputStream = null;
objectOutputStream = null;
inputStream = null;
socket = null;
Log.e(TAG, "文件發(fā)送成功");
return true;
} catch (Exception e) {
Log.e(TAG, "文件發(fā)送異常 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);
}
}
五、校驗(yàn)文件完整性
傳輸文件的完整性主要是通過(guò)計(jì)算文件的MD5碼值來(lái)保證了辞居,在發(fā)送文件前楷怒,即在 WifiClientTask 的 doInBackground 方法中進(jìn)行計(jì)算,將MD5碼值賦給 FileTransfer 模型速侈,通過(guò)如下方法計(jì)算得到
/**
* 作者:leavesC
* 時(shí)間:2019/2/27 23:57
* 描述:
* GitHub:https://github.com/leavesC
* Blog:http://www.reibang.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();
}
}
因?yàn)榭蛻舳藭?huì)將 FileTransfer 傳給服務(wù)器端率寡,所以服務(wù)器端在文件傳輸結(jié)束后,可以重新計(jì)算文件的 MD5碼值倚搬,進(jìn)行對(duì)比以判斷文件是否完整
項(xiàng)目主頁(yè):Android 實(shí)現(xiàn)無(wú)網(wǎng)絡(luò)傳輸文件 冶共,歡迎 star
公眾號(hào):字節(jié)數(shù)組,熱衷于分享 Android 系統(tǒng)源碼解析每界,Jetpack 源碼解析捅僵、熱門開(kāi)源庫(kù)源碼解析等面試必備的知識(shí)點(diǎn)