真实的国产乱ⅩXXX66竹夫人,五月香六月婷婷激情综合,亚洲日本VA一区二区三区,亚洲精品一区二区三区麻豆

成都創(chuàng)新互聯(lián)網(wǎng)站制作重慶分公司

Android實(shí)現(xiàn)無(wú)網(wǎng)絡(luò)傳輸文件的示例代碼

最近的項(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)整理下代碼,分享給大家。

成都創(chuàng)新互聯(lián)公司主營(yíng)武漢網(wǎng)站建設(shè)的網(wǎng)絡(luò)公司,主營(yíng)網(wǎng)站建設(shè)方案,手機(jī)APP定制開(kāi)發(fā),武漢h5成都微信小程序搭建,武漢網(wǎng)站營(yíng)銷(xiāo)推廣歡迎武漢等地區(qū)企業(yè)咨詢

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)

實(shí)現(xiàn)的效果如下所示:

Android 實(shí)現(xiàn)無(wú)網(wǎng)絡(luò)傳輸文件的示例代碼

客戶端.png

Android 實(shí)現(xiàn)無(wú)網(wǎng)絡(luò)傳輸文件的示例代碼

服務(wù)器端.png

一般而言,開(kāi)發(fā)步驟分為以下幾點(diǎn):

  1. 在 AndroidManifest 中聲明相關(guān)權(quán)限(網(wǎng)絡(luò)和文件讀寫(xiě)權(quán)限)
  2. 獲取 WifiP2pManager ,注冊(cè)相關(guān)廣播監(jiān)聽(tīng)Wifi直連的狀態(tài)變化
  3. 指定某一臺(tái)設(shè)備為服務(wù)器(用來(lái)接收文件),創(chuàng)建群組并作為群主存在,在指定端口監(jiān)聽(tīng)客戶端的連接請(qǐng)求,等待客戶端發(fā)起連接請(qǐng)求以及文件傳輸請(qǐng)求
  4. 客戶端(用來(lái)發(fā)送文件)主動(dòng)搜索附近的設(shè)備,加入到服務(wù)器創(chuàng)建的群組,獲取服務(wù)器的IP地址,向其發(fā)起文件傳輸請(qǐng)求
  5. 校驗(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)限。


  
  
  
  
  
  

二、注冊(cè)廣播

與 Wifi P2P 相關(guān)的廣播有以下幾個(gè):

  1. WIFI_P2P_STATE_CHANGED_ACTION( 用于指示 Wifi P2P 是否可用 )
  2. WIFI_P2P_PEERS_CHANGED_ACTION( 對(duì)等節(jié)點(diǎn)列表發(fā)生了變化 )
  3. WIFI_P2P_CONNECTION_CHANGED_ACTION( Wifi P2P 的連接狀態(tài)發(fā)生了改變 )
  4. 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è)備周?chē)目捎迷O(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è)備信息

復(fù)制代碼 代碼如下:

(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 wifiP2pDeviceList);
}

所以,整個(gè)廣播接收器使用到的所有代碼是:

/**
 * 作者:chenZY
 * 時(shí)間:2018/2/9 17:53
 * 描述:
 */
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 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 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)度

/**
 * 作者:葉應(yīng)是葉
 * 時(shí)間:2018/2/15 8:51
 * 描述:客戶端發(fā)送文件
 */
public class WifiClientTask extends AsyncTask {
  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ì)算得到

/**
 * 作者:葉應(yīng)是葉
 * 時(shí)間:2018/2/14 21:16
 * 描述:
 */
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ì)比以判斷文件是否完整

這里分享下上述代碼:Android 實(shí)現(xiàn)無(wú)網(wǎng)絡(luò)傳輸文件 

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持創(chuàng)新互聯(lián)。


網(wǎng)站名稱(chēng):Android實(shí)現(xiàn)無(wú)網(wǎng)絡(luò)傳輸文件的示例代碼
瀏覽地址:http://weahome.cn/article/gojhhs.html

其他資訊

在線咨詢

微信咨詢

電話咨詢

028-86922220(工作日)

18980820575(7×24)

提交需求

返回頂部