国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 系統 > Android > 正文

Android實現簡單的文件下載與上傳

2019-10-21 21:32:01
字體:
來源:轉載
供稿:網友

文件下載

/** * 下載服務 IntentService  * 生命周期: * 1>當第一次啟動IntentService時,Android容器 *  將會創建IntentService對象。 * 2>IntentService將會在工作線程中輪循消息隊列, *  執行每個消息對象中的業務邏輯。 * 3>如果消息隊列中依然有消息,則繼續執行, *  如果消息隊列中的消息已經執行完畢, *  IntentService將會自動銷毀,執行onDestroy方法。 */public class DownloadService extends IntentService{  private static final int NOTIFICATION_ID = 100;  public DownloadService(){    super("download");  }  public DownloadService(String name) {    super(name);  }  /**   * 該方法中的代碼將會在工作線程中執行   * 每當調用startService啟動IntentService后,   * IntentService將會把OnHandlerIntent中的   * 業務邏輯放入消息隊列等待執行。   * 當工作線程輪循到該消息對象時,將會   * 執行該方法。   */  protected void onHandleIntent(Intent intent) {    //發送Http請求 執行下載業務    //1. 獲取音樂的路徑    String url=intent.getStringExtra("url");    String bit=intent.getStringExtra("bit");    String    //2. 構建File對象,用于保存音樂文件    //   /mnt/sdcard/Music/_64/歌名.mp3    File targetFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC),"_"+bit+"/"+title+".mp3" );             if(targetFile.exists()){      Log.i("info", "音樂已存在");      return;    }    if(!targetFile.getParentFile().exists()){      targetFile.getParentFile().mkdirs();    }    try {      sendNotification("音樂開始下載", "音樂開始下載");      //3. 發送Http請求,獲取InputStream      InputStream is = HttpUtils.getInputStream(url);      //4. 邊讀取邊保存到File對象中      FileOutputStream fos = new FileOutputStream(targetFile);      byte[] buffer = new byte[1024*100];      int length=0;      int current = 0;      int total = Integer.parseInt(intent.getStringExtra("total"));      while((length=is.read(buffer)) != -1){        fos.write(buffer, 0, length);        fos.flush();        current += length;        //通知下載的進度        double progress = Math.floor(1000.0*current/total)/10;        sendNotification("音樂開始下載", "下載進度:"+progress+"%");      }      //5. 文件下載完成      fos.close();      cancelNotification(); //重新出現滾動消息      sendNotification("音樂下載完成", "音樂下載完畢");    } catch (Exception e) {      e.printStackTrace();    }  }  /**   * 發通知   */  public void sendNotification(String ticker, String text){    NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);    Notification.Builder builder = new Notification.Builder(this);    builder.setSmallIcon(R.drawable.ic_launcher)      .setContentTitle("音樂下載")      .setContentText(text)      .setTicker(ticker);    Notification n = builder.build();    manager.notify(NOTIFICATION_ID, n);  }  /**   * 取消通知   */  public void cancelNotification(){    NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);    manager.cancel(NOTIFICATION_ID);  }    }

文件上傳

 /**    * 上傳文件    * @param uploadFile    */   private void uploadFile(final File uploadFile) {     new Thread(new Runnable() {            @Override       public void run() {         try {           uploadbar.setMax((int)uploadFile.length());           String souceid = logService.getBindId(uploadFile);           String head = "Content-Length="+ uploadFile.length() + ";filename="+ uploadFile.getName() + ";sourceid="+             (souceid==null? "" : souceid)+"/r/n";           Socket socket = new Socket("192.168.1.78",7878);           OutputStream outStream = socket.getOutputStream();           outStream.write(head.getBytes());           PushbackInputStream inStream = new PushbackInputStream(socket.getInputStream());             String response = StreamTool.readLine(inStream);           String[] items = response.split(";");           String responseid = items[0].substring(items[0].indexOf("=")+1);           String position = items[1].substring(items[1].indexOf("=")+1);           if(souceid==null){//代表原來沒有上傳過此文件,往數據庫添加一條綁定記錄             logService.save(responseid, uploadFile);           }           RandomAccessFile fileOutStream = new RandomAccessFile(uploadFile, "r");           fileOutStream.seek(Integer.valueOf(position));           byte[] buffer = new byte[1024];           int len = -1;           int length = Integer.valueOf(position);           while(start&&(len = fileOutStream.read(buffer)) != -1){             outStream.write(buffer, 0, len);             length += len;             Message msg = new Message();             msg.getData().putInt("size", length);             handler.sendMessage(msg);           }           fileOutStream.close();           outStream.close();           inStream.close();           socket.close();           if(length==uploadFile.length()) logService.delete(uploadFile);         } catch (Exception e) {           e.printStackTrace();         }       }     }).start();   } } 

總結

以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對VEVB武林網的支持。


注:相關教程知識閱讀請移步到Android開發頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 读书| 淮南市| 惠安县| 仙游县| 景德镇市| 西平县| 永新县| 松江区| 卢龙县| 射阳县| 综艺| 平乐县| 长海县| 吉安市| 上杭县| 洱源县| 平安县| 交口县| 桐柏县| 鄱阳县| 宽城| 信阳市| 平武县| 涿州市| 开封市| 南部县| 德钦县| 甘谷县| 同江市| 庆云县| 孝感市| 绍兴县| 浏阳市| 福建省| 漳平市| 盐津县| 元朗区| 沈阳市| 凤台县| 新密市| 营口市|