欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Android中實(shí)現(xiàn)下載URL地址的網(wǎng)絡(luò)資源的實(shí)例分享

 更新時(shí)間:2016年04月24日 15:53:53   作者:劍蕭舞蝶  
這篇文章主要介紹了Android中實(shí)現(xiàn)下載URL地址的網(wǎng)絡(luò)資源的實(shí)例,其中還有一個(gè)進(jìn)行多線程下載的Java代碼示例,非常典型,需要的朋友可以參考下

通過URL來獲取網(wǎng)絡(luò)資源并下載資源簡(jiǎn)單實(shí)例:

package com.android.xiong.urltest; 
 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.OutputStream; 
import java.net.MalformedURLException; 
import java.net.URL; 
 
import android.app.Activity; 
import android.graphics.Bitmap; 
import android.graphics.BitmapFactory; 
import android.os.Bundle; 
import android.os.Handler; 
import android.os.Message; 
import android.view.Menu; 
import android.widget.ImageView; 
 
public class MainActivity extends Activity { 
  ImageView show; 
  Bitmap bitmap; 
  Handler handler = new Handler() { 
 
    @Override 
    public void handleMessage(Message msg) { 
      if (msg.what == 0x123) { 
        // 使用ImageView顯示該圖片 
        show.setImageBitmap(bitmap); 
 
      } 
    } 
 
  }; 
 
  @Override 
  protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    show = (ImageView) findViewById(R.id.show); 
 
    new Thread() { 
 
      @Override 
      public void run() { 
        // 定義一個(gè)URL對(duì)象 
        URL url; 
        try { 
          url = new URL( 
              "http://img1.gtimg.com/news/pics/hv1/37/195/1468/95506462.jpg"); 
          // 打開該URL的資源輸入流 
          InputStream is = url.openStream(); 
          // 從InputStream中解析出圖片 
          bitmap = BitmapFactory.decodeStream(is); 
          // 發(fā)送消息 
          handler.sendEmptyMessage(0x123); 
          is.close(); 
          // 再次打開RL對(duì)應(yīng)的資源輸入流 
          is = url.openStream(); 
          // 打開手機(jī)文件對(duì)應(yīng)的輸出流 
          OutputStream os = openFileOutput("KEQIANG.JPG", MODE_APPEND); 
          byte[] buff = new byte[1024]; 
          int hasRead = 0; 
          // 將URL資源下載到本地 
          while ((hasRead = is.read(buff)) > 0) { 
            os.write(buff, 0, hasRead); 
          } 
          is.close(); 
          os.close(); 
        } catch (MalformedURLException e) { 
          // TODO Auto-generated catch block 
          e.printStackTrace(); 
        } catch (IOException e) { 
          // TODO Auto-generated catch block 
          e.printStackTrace(); 
        } 
 
      } 
 
    }.start(); 
  } 
 
  @Override 
  public boolean onCreateOptionsMenu(Menu menu) { 
    // Inflate the menu; this adds items to the action bar if it is present. 
    getMenuInflater().inflate(R.menu.main, menu); 
    return true; 
  } 
 
} 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
  xmlns:tools="http://schemas.android.com/tools" 
  android:layout_width="match_parent" 
  android:layout_height="match_parent" 
  android:orientation="vertical" 
  tools:context=".MainActivity" > 
 
  <ImageView  
    android:id="@+id/show" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:contentDescription="@string/hello_world"/> 
 
</LinearLayout> 

網(wǎng)絡(luò)資源多線程下載:

package com.example.threaddown; 
 
import java.util.Timer; 
import java.util.TimerTask; 
 
import android.app.Activity; 
import android.os.Bundle; 
import android.os.Handler; 
import android.os.Message; 
import android.view.Menu; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.widget.Button; 
import android.widget.EditText; 
import android.widget.ProgressBar; 
 
public class MainActivity extends Activity { 
 
  EditText url; 
  EditText target; 
  Button downBn; 
  ProgressBar bar; 
  DownUtil downUtil; 
  private int mDownStatus; 
 
  @Override 
  protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    // 獲取程序界面中的三個(gè)界面控制 
    url = (EditText) findViewById(R.id.url); 
    target = (EditText) findViewById(R.id.target); 
    downBn = (Button) findViewById(R.id.downBn); 
    bar = (ProgressBar) findViewById(R.id.br); 
    // 創(chuàng)建一個(gè)Handler對(duì)象 
    final Handler handler = new Handler() { 
 
      @Override 
      public void handleMessage(Message msg) { 
        if (msg.what == 0x123) { 
          bar.setProgress(mDownStatus); 
        } 
      } 
 
    }; 
    downBn.setOnClickListener(new OnClickListener() { 
 
      @Override 
      public void onClick(View v) { 
        // 初始化DownUtil對(duì)象 
        downUtil = new DownUtil(url.getText().toString(), target 
            .getText().toString(), 6); 
        new Thread() { 
 
          @Override 
          public void run() { 
            try { 
              // 開始下載 
              downUtil.download(); 
 
            } catch (Exception e) { 
              e.printStackTrace(); 
            } 
            // 定義每秒調(diào)度獲取一次系統(tǒng)的完成進(jìn)度 
            final Timer timer = new Timer(); 
            timer.schedule(new TimerTask() { 
 
              @Override 
              public void run() { 
                // 獲取下載任務(wù)的完成比例 
                double completeRate = downUtil 
                    .getCompleteRate(); 
                mDownStatus = (int) (completeRate * 1000); 
                // 發(fā)送消息通知屆滿更新的進(jìn)度條 
                handler.sendEmptyMessage(0x123); 
                // 下載完成之后取消任務(wù)進(jìn)度 
                if (mDownStatus >= 100) { 
                  timer.cancel(); 
                } 
              } 
            }, 0, 1000); 
          } 
 
        }.start(); 
      } 
    }); 
  } 
 
  @Override 
  public boolean onCreateOptionsMenu(Menu menu) { 
    // Inflate the menu; this adds items to the action bar if it is present. 
    getMenuInflater().inflate(R.menu.main, menu); 
    return true; 
  } 
 
} 
package com.example.threaddown; 
 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.RandomAccessFile; 
import java.net.HttpURLConnection; 
import java.net.MalformedURLException; 
import java.net.URL; 
 
public class DownUtil { 
 
  // 定義下載資源的路徑 
  private String path; 
  // 指定所下載的文件的保存位置 
  private String targetFile; 
  // 定義需要使用多少線程下載資源 
  private int threadNum; 
  // 定義下載的線程對(duì)象 
  private DownThread[] threads; 
  // 定義下載的文件總大小 
  private int fileSize; 
 
  public DownUtil(String path, String targetFile, int threadNum) { 
    this.path = path; 
    this.targetFile = targetFile; 
    this.threadNum = threadNum; 
  } 
 
  public void download() throws IOException { 
    URL url = new URL(path); 
    HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 
    conn.setConnectTimeout(5000); 
    conn.setRequestMethod("GET"); 
    conn.setRequestProperty("Accept", "*/*"); 
    conn.setRequestProperty("Accept-Language", "zh-CN"); 
    conn.setRequestProperty("Charset", "UTF-8"); 
    conn.setRequestProperty("Connection", "Keep-Alive"); 
    // 得到文件的大小 
    fileSize = conn.getContentLength(); 
    conn.disconnect(); 
    int currentPartsSize = fileSize / threadNum + 1; 
    RandomAccessFile file = new RandomAccessFile(targetFile, "rw"); 
    // 設(shè)置本地文件的大小 
    file.setLength(fileSize); 
    file.close(); 
    for (int i = 0; i < threadNum; i++) { 
      // 計(jì)算每條線程的下載位置 
      int startPos = i * currentPartsSize; 
      // 每個(gè)線程使用一個(gè)RandomAccessFile進(jìn)行下載 
      RandomAccessFile current = new RandomAccessFile(targetFile, "rw"); 
      // 定義該線程的下載位置 
      current.seek(startPos); 
      // 創(chuàng)建下載線程 
      threads[i] = new DownThread(startPos, currentPartsSize, current); 
      // 啟動(dòng)線程下載 
      threads[i].start(); 
    } 
 
  } 
 
  // 獲取下載的完成百分比 
  public double getCompleteRate() { 
    // 統(tǒng)計(jì)多條線程已經(jīng)下載的總大小 
    int sumSize = 0; 
    for (int i = 0; i < threadNum; i++) { 
      sumSize += threads[i].length; 
    } 
    return sumSize * 1.0 / fileSize; 
  } 
 
  private class DownThread extends Thread { 
    // 定義當(dāng)前線程下載的位置 
    private int startPos; 
    // 定義當(dāng)前線程下載文件的大小 
    private int currentPartsSize; 
    // 當(dāng)前線程下載的文件塊 
    private RandomAccessFile currentPart; 
    // 定義該線程已下載的字節(jié)數(shù) 
    private int length; 
 
    public DownThread(int startPos, int currentPartsSize, 
        RandomAccessFile currentPart) { 
      this.startPos = startPos; 
      this.currentPart = currentPart; 
      this.currentPartsSize = currentPartsSize; 
 
    } 
 
    @Override 
    public void run() { 
      try { 
        URL url = new URL(path); 
        HttpURLConnection conn = (HttpURLConnection) url 
            .openConnection(); 
        conn.setConnectTimeout(5000); 
        conn.setRequestMethod("GET"); 
        conn.setRequestProperty("Accept", "*/*"); 
        conn.setRequestProperty("Accept-Language", "zh-CN"); 
        conn.setRequestProperty("Charset", "UTF-8"); 
        conn.setRequestProperty("Connection", "Keep-Alive"); 
        InputStream in = conn.getInputStream(); 
        in.skip(startPos); 
        int hasRead = 0; 
        byte[] buffer = new byte[1024]; 
        // 讀取網(wǎng)絡(luò)數(shù)據(jù),并寫入本地文件 
        while (length < currentPartsSize 
            && (hasRead = in.read(buffer)) > 0) { 
          currentPart.write(buffer, 0, hasRead); 
          // 累計(jì)該線程下載的總大小 
          length += hasRead; 
        } 
        currentPart.close(); 
        in.close(); 
 
      } catch (Exception e) { 
        e.printStackTrace(); 
      } 
 
    } 
 
  } 
 
} 


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
  xmlns:tools="http://schemas.android.com/tools" 
  android:layout_width="match_parent" 
  android:layout_height="match_parent" 
  android:orientation="vertical" 
  tools:context=".MainActivity" > 
 
  <EditText 
    android:id="@+id/url" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:text="http://ksoap2-android.googlecode.com/svn/m2-repo/com/google/code/ksoap2-android/ksoap2-android-assembly/3.1.0/ksoap2-android-assembly-3.1.0-jar-with-dependencies.jar" /> 
 
  <EditText 
    android:id="@+id/target" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content"  
    android:text="/mnt/sdcard/"/> 
 
  <Button 
    android:id="@+id/downBn" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:text="down" /> 
 
  <ProgressBar 
    android:id="@+id/br" 
    style="?android:attr/progressBarStyleHorizontal" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" /> 
 
</LinearLayout> 

<!-- 在SD卡中創(chuàng)建與刪除文件的權(quán)限 --> 
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" /> 
<!-- 在SD開中寫入數(shù)據(jù)的權(quán)限 --> 
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 
<!-- 訪問網(wǎng)路的權(quán)限 --> 
<uses-permission android:name="android.permission.INTERNET" /> 

相關(guān)文章

  • Android帶進(jìn)度條的下載圖片示例(AsyncTask異步任務(wù))

    Android帶進(jìn)度條的下載圖片示例(AsyncTask異步任務(wù))

    本文主要介紹Android帶進(jìn)度條的下載圖片示例(AsyncTask異步任務(wù))的方法解析。具有很好的參考價(jià)值。下面跟著小編一起來看下吧
    2017-04-04
  • Android自定義指示器時(shí)間軸效果實(shí)例代碼詳解

    Android自定義指示器時(shí)間軸效果實(shí)例代碼詳解

    指示器時(shí)間軸在外賣、購物類的APP里會(huì)經(jīng)常用到,效果大家都知道的差不多吧,下面小編通過實(shí)例代碼給大家分享Android自定義指示器時(shí)間軸效果,需要的朋友參考下吧
    2017-12-12
  • Android開發(fā)實(shí)現(xiàn)圖片大小與質(zhì)量壓縮及保存

    Android開發(fā)實(shí)現(xiàn)圖片大小與質(zhì)量壓縮及保存

    這篇文章主要為大家介紹了Android開發(fā)實(shí)現(xiàn)圖片大小與質(zhì)量壓縮及保存的方法,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2022-04-04
  • Android使用注解代替枚舉節(jié)省系統(tǒng)內(nèi)存開銷的方法

    Android使用注解代替枚舉節(jié)省系統(tǒng)內(nèi)存開銷的方法

    在本篇文章里小編給大家整理的是關(guān)于Android使用注解代替枚舉節(jié)省系統(tǒng)內(nèi)存開銷的方法和實(shí)例,需要的朋友們參考下。
    2020-01-01
  • Android仿QQ首頁ListView左滑置頂、刪除功能

    Android仿QQ首頁ListView左滑置頂、刪除功能

    這篇文章主要為大家詳細(xì)介紹了Android仿QQ首頁ListView左滑置頂、刪除功能,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2017-12-12
  • 實(shí)例探究Android開發(fā)中Fragment狀態(tài)的保存與恢復(fù)方法

    實(shí)例探究Android開發(fā)中Fragment狀態(tài)的保存與恢復(fù)方法

    這篇文章主要介紹了實(shí)例探究Android開發(fā)中Fragment狀態(tài)的保存與恢復(fù)方法,或許開發(fā)者們對(duì)Fragment的操作都比較熟悉,但onSaveInstanceState()方法并不能夠很好地保存Fragment狀態(tài),需要的朋友可以參考下
    2016-04-04
  • 最新評(píng)論