Android中實(shí)現(xiàn)下載URL地址的網(wǎng)絡(luò)資源的實(shí)例分享
通過(guò)URL來(lái)獲取網(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");
// 打開(kāi)該URL的資源輸入流
InputStream is = url.openStream();
// 從InputStream中解析出圖片
bitmap = BitmapFactory.decodeStream(is);
// 發(fā)送消息
handler.sendEmptyMessage(0x123);
is.close();
// 再次打開(kāi)RL對(duì)應(yīng)的資源輸入流
is = url.openStream();
// 打開(kāi)手機(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 {
// 開(kāi)始下載
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ù),并寫(xiě)入本地文件
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開(kāi)中寫(xiě)入數(shù)據(jù)的權(quán)限 --> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <!-- 訪問(wèn)網(wǎng)路的權(quán)限 --> <uses-permission android:name="android.permission.INTERNET" />
相關(guān)文章
Android實(shí)現(xiàn)極簡(jiǎn)打開(kāi)攝像頭
這篇文章主要為大家詳細(xì)介紹了Android實(shí)現(xiàn)極簡(jiǎn)打開(kāi)攝像頭,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-03-03
詳解Android中Intent對(duì)象與Intent Filter過(guò)濾匹配過(guò)程
這篇文章主要介紹了Android中Intent對(duì)象與Intent Filter過(guò)濾匹配過(guò)程,感興趣的小伙伴們可以參考一下2015-12-12
Android系統(tǒng)的五種數(shù)據(jù)存儲(chǔ)形式實(shí)例(二)
Android系統(tǒng)有五種數(shù)據(jù)存儲(chǔ)形式,分別是文件存儲(chǔ)、SP存儲(chǔ)、數(shù)據(jù)庫(kù)存儲(chǔ)、contentprovider 內(nèi)容提供者、網(wǎng)絡(luò)存儲(chǔ)。本文介紹了Android系統(tǒng)的五種數(shù)據(jù)存儲(chǔ)形式,有興趣的可以了解一下。2016-12-12
Android 使用mediaplayer播放res/raw文件夾中的音樂(lè)的實(shí)例
這篇文章主要介紹了Android 使用mediaplayer播放res/raw文件夾中的音樂(lè)的實(shí)例的相關(guān)資料,需要的朋友可以參考下2017-04-04
Android中仿IOS提示框的實(shí)現(xiàn)方法
下面小編就為大家分享一篇Android中仿IOS提示框的實(shí)現(xiàn)方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-01-01
RecyclerView嵌套R(shí)ecyclerView滑動(dòng)卡頓的解決方法
這篇文章主要為大家詳細(xì)介紹了RecyclerView嵌套R(shí)ecyclerView滑動(dòng)卡頓的解決方法,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-12-12
Android 實(shí)現(xiàn)云知聲版離線語(yǔ)音合成
這篇文章主要介紹了Android 實(shí)現(xiàn)云知聲版離線語(yǔ)音合成,目前云知聲提供免費(fèi)的離線TTS,功能也比較簡(jiǎn)單,合成的語(yǔ)音也比較生硬,如果對(duì)合成的語(yǔ)音要求不高的話可以考慮接入。具體合成需要的小伙伴可以參考下面文章內(nèi)容2022-06-06
Android開(kāi)發(fā)之創(chuàng)建可點(diǎn)擊的Button實(shí)現(xiàn)方法
這篇文章主要介紹了Android創(chuàng)建可點(diǎn)擊的Button實(shí)現(xiàn)方法,實(shí)例分析了Android創(chuàng)建button按鈕過(guò)程中的界面配置,功能實(shí)現(xiàn)與相關(guān)注意事項(xiàng),需要的朋友可以參考下2016-03-03
關(guān)于Android SDCard存儲(chǔ)的問(wèn)題
本篇文章小編為大家介紹,關(guān)于Android SDCard存儲(chǔ)的問(wèn)題。需要的朋友參考下2013-04-04

