Android中实现下载URL地址的网络资源的实例分享
作者:剑萧舞蝶 时间:2023-07-30 03:56:58
通过URL来获取网络资源并下载资源简单实例:
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() {
// 定义一个URL对象
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);
// 发送消息
handler.sendEmptyMessage(0x123);
is.close();
// 再次打开RL对应的资源输入流
is = url.openStream();
// 打开手机文件对应的输出流
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>
网络资源多线程下载:
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);
// 获取程序界面中的三个界面控制
url = (EditText) findViewById(R.id.url);
target = (EditText) findViewById(R.id.target);
downBn = (Button) findViewById(R.id.downBn);
bar = (ProgressBar) findViewById(R.id.br);
// 创建一个Handler对象
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对象
downUtil = new DownUtil(url.getText().toString(), target
.getText().toString(), 6);
new Thread() {
@Override
public void run() {
try {
// 开始下载
downUtil.download();
} catch (Exception e) {
e.printStackTrace();
}
// 定义每秒调度获取一次系统的完成进度
final Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
// 获取下载任务的完成比例
double completeRate = downUtil
.getCompleteRate();
mDownStatus = (int) (completeRate * 1000);
// 发送消息通知届满更新的进度条
handler.sendEmptyMessage(0x123);
// 下载完成之后取消任务进度
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;
// 定义下载的线程对象
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");
// 设置本地文件的大小
file.setLength(fileSize);
file.close();
for (int i = 0; i < threadNum; i++) {
// 计算每条线程的下载位置
int startPos = i * currentPartsSize;
// 每个线程使用一个RandomAccessFile进行下载
RandomAccessFile current = new RandomAccessFile(targetFile, "rw");
// 定义该线程的下载位置
current.seek(startPos);
// 创建下载线程
threads[i] = new DownThread(startPos, currentPartsSize, current);
// 启动线程下载
threads[i].start();
}
}
// 获取下载的完成百分比
public double getCompleteRate() {
// 统计多条线程已经下载的总大小
int sumSize = 0;
for (int i = 0; i < threadNum; i++) {
sumSize += threads[i].length;
}
return sumSize * 1.0 / fileSize;
}
private class DownThread extends Thread {
// 定义当前线程下载的位置
private int startPos;
// 定义当前线程下载文件的大小
private int currentPartsSize;
// 当前线程下载的文件块
private RandomAccessFile currentPart;
// 定义该线程已下载的字节数
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];
// 读取网络数据,并写入本地文件
while (length < currentPartsSize
&& (hasRead = in.read(buffer)) > 0) {
currentPart.write(buffer, 0, hasRead);
// 累计该线程下载的总大小
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卡中创建与删除文件的权限 -->
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
<!-- 在SD开中写入数据的权限 -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<!-- 访问网路的权限 -->
<uses-permission android:name="android.permission.INTERNET" />
标签:Android,下载
0
投稿
猜你喜欢
详解Android自定义控件属性
2023-09-27 18:00:34
springmvc不进入Controller导致404的问题
2023-03-18 01:29:20
Lombok使用@Tolerate实现冲突兼容问题
2021-06-27 06:50:55
Java Swing 多线程加载图片(保证顺序一致)
2023-10-26 10:10:36
Android编程实现加载等待ProgressDialog的方法
2022-09-11 21:12:11
Activiti开发环境的配置
2021-07-31 21:57:51
Java性能优化技巧汇总
2023-01-05 16:26:31
java集合求和最大值最小值示例分享
2022-10-11 04:15:10
简单易懂的java8新特性之lambda表达式知识总结
2023-04-14 23:44:42
AndroidStudio 3.6 中 R.layout 找不到对应的xml文件问题及解决方法
2023-05-19 08:22:02
Java自定义标签用法实例分析
2023-02-28 21:58:55
Spring注解与P/C命名空间超详细解析
2022-08-04 19:42:34
Java语法糖之个数可变的形参的实现
2023-12-05 00:13:20
C#中判断某类型是否可以进行隐式类型转换
2023-03-28 15:29:36
Java中ArrayList集合的常用方法大全
2023-09-01 15:23:30
Java swing实现支持录音等功能的钢琴程序
2022-08-21 12:30:16
Java设计模式之桥接模式
2021-08-31 05:56:02
IDEA集成JProfiler11可视化工具的详细流程(安装、集成、测试)
2021-12-12 04:05:35
Java中使用fileupload组件实现文件上传功能的实例代码
2021-11-17 09:20:33
c# 获取照片的经纬度和时间的示例代码
2022-03-22 18:21:54