Android開發(fā)之異步獲取并下載網(wǎng)絡(luò)資源
來源:易賢網(wǎng) 閱讀:939 次 日期:2015-02-10 10:12:09
溫馨提示:易賢網(wǎng)小編為您整理了“Android開發(fā)之異步獲取并下載網(wǎng)絡(luò)資源”,方便廣大網(wǎng)友查閱!

1)從指定的URL獲取對(duì)應(yīng)的流

既然要獲取網(wǎng)絡(luò)資源,那么首先得有個(gè)URL,那么這里我首先封裝一個(gè)打開URL連接獲取到的InputStream 流,這樣一來無論是圖片資源還是文本文件資源都可以使用該接口方法來獲取流。

該功能主要應(yīng)用URLConnection和HttpURLConnection來實(shí)現(xiàn),具體實(shí)現(xiàn)方案如下:

private InputStream openHttpConnection(String urlString) throws IOException{

InputStream in = null;

int response = -1;

URL url = new URL(urlString);

URLConnection conn = url.openConnection();

if(!(conn instanceof HttpURLConnection)){

throw new IOException("It is not an HTTP connection");

}

try {

HttpURLConnection httpConn = (HttpURLConnection) conn;

httpConn.setAllowUserInteraction(false);

httpConn.setInstanceFollowRedirects(true);

httpConn.setRequestMethod("GET");

httpConn.connect();

response = httpConn.getResponseCode();

if (response == HttpURLConnection.HTTP_OK) {

in = httpConn.getInputStream();

}

} catch (Exception ex) {

Log.v("Networking",ex.getLocalizedMessage());

throw new IOException("Error connecting");

}

return in;

}

(2)封裝了上面的獲取流方法接口后,我們就可以利用上面封裝的方法來獲取并下載相應(yīng)圖片和文本文件內(nèi)容了

獲取并下載圖片資源方法:

private Bitmap downloadImage(String url){

Bitmap bitmap = null;

InputStream in = null;

try {

in = openHttpConnection(url);

bitmap = BitmapFactory.decodeStream(in);

in.close();

} catch (IOException e) {

// TODO Auto-generated catch block

Log.v("NetworkingActivity", e.getLocalizedMessage());

}

return bitmap;

}

獲取并下載文本內(nèi)容方法:

private String downloadText(String url){

int BUFFER_SIZE = 2000;

InputStream is = null;

try {

is = openHttpConnection(url);

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

return "";

}

InputStreamReader isr = new InputStreamReader(is);

int charRead;

String str="";

char[] inputBuffer = new char[BUFFER_SIZE];

try {

while((charRead=isr.read(inputBuffer))>0){

String readString = String.copyValueOf(inputBuffer, 0, charRead);

str += readString;

inputBuffer = new char[BUFFER_SIZE];

}

is.close();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

return "";

}

return str;

}

(3)在獲取下載圖片資源和文本內(nèi)容資源方法都完成后,現(xiàn)在就可以開始下載任務(wù)了,為了防止等待效應(yīng),一般采用異步任務(wù)來下載網(wǎng)絡(luò)資源。

對(duì)對(duì)應(yīng)的下載資源任務(wù)封裝各自的異步下載任務(wù)即可。下面就是實(shí)現(xiàn)異步下載任務(wù)的方案:

異步下載圖片任務(wù):

private class DownloadImageTask extends AsyncTask<String, Bitmap, Long>{

long imagesCount = 0;

ProgressBar progressBar;

public DownloadImageTask(ProgressBar pBar){

this.progressBar = pBar;

}

@Override

protected Long doInBackground(String... urls) {

// TODO Auto-generated method stub

for(int i = 0; i < urls.length;i++){

Bitmap imageDownloaded = downloadImage(urls[i]);

if(imageDownloaded!=null){

imagesCount ++;

publishProgress(imageDownloaded);

try {

Thread.sleep(300);

} catch (InterruptedException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}

return imagesCount;

}

//display the image downloaded

@Override

protected void onProgressUpdate(Bitmap... bitmaps) {

// TODO Auto-generated method stub

ivImg.setImageBitmap(bitmaps[0]);

progressBar.setProgress((int) imagesCount*10);

}

//when all the images have been downloaded

@Override

protected void onPostExecute(Long imageDownloaded) {

// TODO Auto-generated method stub

String str = "下載完成!一共下載了"+imagesCount +"張圖片";

Toast.makeText(getBaseContext(), str, Toast.LENGTH_SHORT).show();

}

}

異步下載文本文件內(nèi)容任務(wù):

private class DownloadTextTask extends AsyncTask<String, Void, String>{

@Override

protected void onPostExecute(String result) {

// TODO Auto-generated method stub

Toast.makeText(getBaseContext(), result, Toast.LENGTH_LONG).show();

}

@Override

protected String doInBackground(String... urls) {

// TODO Auto-generated method stub

return downloadText(urls[0]);

}

}

這樣一來,異步下載網(wǎng)絡(luò)資源就完成了。

下面為了讀者方便測(cè)試,下面提供本文實(shí)例代碼中的相關(guān)網(wǎng)絡(luò)資源URL,以方便大家自己測(cè)試使用。其余非核心代碼就不在貼出來,望讀者見諒。

//圖片下載URLs

private String[] mUrl =

{

"",

""

};

progressBar = (ProgressBar) findViewById(R.id.progressBar);

progressBar.setMax(mUrl.length*10);

progressBar.setVisibility(View.VISIBLE);

//異步下載圖片任務(wù)

DownloadImageTask task = new DownloadImageTask(progressBar);

task.execute(mUrl);

//文本文件URL

String strUrl = "";

//異步下載文本文件內(nèi)容任務(wù)

new DownloadTextTask().execute(strUrl);

更多信息請(qǐng)查看IT技術(shù)專欄

更多信息請(qǐng)查看數(shù)據(jù)庫(kù)
易賢網(wǎng)手機(jī)網(wǎng)站地址:Android開發(fā)之異步獲取并下載網(wǎng)絡(luò)資源
由于各方面情況的不斷調(diào)整與變化,易賢網(wǎng)提供的所有考試信息和咨詢回復(fù)僅供參考,敬請(qǐng)考生以權(quán)威部門公布的正式信息和咨詢?yōu)闇?zhǔn)!

2025國(guó)考·省考課程試聽報(bào)名

  • 報(bào)班類型
  • 姓名
  • 手機(jī)號(hào)
  • 驗(yàn)證碼
關(guān)于我們 | 聯(lián)系我們 | 人才招聘 | 網(wǎng)站聲明 | 網(wǎng)站幫助 | 非正式的簡(jiǎn)要咨詢 | 簡(jiǎn)要咨詢須知 | 新媒體/短視頻平臺(tái) | 手機(jī)站點(diǎn) | 投訴建議
工業(yè)和信息化部備案號(hào):滇ICP備2023014141號(hào)-1 云南省教育廳備案號(hào):云教ICP備0901021 滇公網(wǎng)安備53010202001879號(hào) 人力資源服務(wù)許可證:(云)人服證字(2023)第0102001523號(hào)
云南網(wǎng)警備案專用圖標(biāo)
聯(lián)系電話:0871-65099533/13759567129 獲取招聘考試信息及咨詢關(guān)注公眾號(hào):hfpxwx
咨詢QQ:1093837350(9:00—18:00)版權(quán)所有:易賢網(wǎng)
云南網(wǎng)警報(bào)警專用圖標(biāo)