Instance Sharing of Network Resources for Downloading URL Address in Android
- 2021-07-09 09:11:13
- OfStack
Use URL to get network resources and download a simple example of resources:
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) {
// Use ImageView Display the picture
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() {
// Definition 1 A URL Object
URL url;
try {
url = new URL(
"http://img1.gtimg.com/news/pics/hv1/37/195/1468/95506462.jpg");
// Open the URL Resource input stream of
InputStream is = url.openStream();
// From InputStream Parse out the picture in
bitmap = BitmapFactory.decodeStream(is);
// Send a message
handler.sendEmptyMessage(0x123);
is.close();
// Open again RL Corresponding resource input stream
is = url.openStream();
// Open the output stream corresponding to the mobile phone file
OutputStream os = openFileOutput("KEQIANG.JPG", MODE_APPEND);
byte[] buff = new byte[1024];
int hasRead = 0;
// Will URL Resources are downloaded locally
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>
Multi-threaded download of network resources:
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);
// Object in the program interface 3 Interface control
url = (EditText) findViewById(R.id.url);
target = (EditText) findViewById(R.id.target);
downBn = (Button) findViewById(R.id.downBn);
bar = (ProgressBar) findViewById(R.id.br);
// Create 1 A Handler Object
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) {
// Initialization DownUtil Object
downUtil = new DownUtil(url.getText().toString(), target
.getText().toString(), 6);
new Thread() {
@Override
public void run() {
try {
// Start downloading
downUtil.download();
} catch (Exception e) {
e.printStackTrace();
}
// Defining Scheduled Per Second Acquisition 1 Completion progress of subsystem
final Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
// Get the completion ratio of download tasks
double completeRate = downUtil
.getCompleteRate();
mDownStatus = (int) (completeRate * 1000);
// Send a message to notify the progress bar of expiration update
handler.sendEmptyMessage(0x123);
// Cancel the task progress after the download is complete
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 {
// Define the path to download resources
private String path;
// Specify where to save downloaded files
private String targetFile;
// Define how many threads need to be used to download resources
private int threadNum;
// Define the thread object for download
private DownThread[] threads;
// Define the total size of downloaded files
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");
// Get the size of the file
fileSize = conn.getContentLength();
conn.disconnect();
int currentPartsSize = fileSize / threadNum + 1;
RandomAccessFile file = new RandomAccessFile(targetFile, "rw");
// Set the size of the local file
file.setLength(fileSize);
file.close();
for (int i = 0; i < threadNum; i++) {
// Calculate the download location of each thread
int startPos = i * currentPartsSize;
// Each thread uses 1 A RandomAccessFile Download
RandomAccessFile current = new RandomAccessFile(targetFile, "rw");
// Define the download location of this thread
current.seek(startPos);
// Create a download thread
threads[i] = new DownThread(startPos, currentPartsSize, current);
// Start thread download
threads[i].start();
}
}
// Get the download completion percentage
public double getCompleteRate() {
// Count the total size downloaded by multiple threads
int sumSize = 0;
for (int i = 0; i < threadNum; i++) {
sumSize += threads[i].length;
}
return sumSize * 1.0 / fileSize;
}
private class DownThread extends Thread {
// Defines the location of the current thread download
private int startPos;
// Defines the size of the file downloaded by the current thread
private int currentPartsSize;
// File block downloaded by current thread
private RandomAccessFile currentPart;
// Defines the number of bytes downloaded by this thread
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];
// Read network data and write to local files
while (length < currentPartsSize
&& (hasRead = in.read(buffer)) > 0) {
currentPart.write(buffer, 0, hasRead);
// Accumulate the total download size of this thread
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>
<!-- In SD Permissions to create and delete files in the card -->
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
<!-- In SD Permission to write data in open -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<!-- Permissions to access the network -->
<uses-permission android:name="android.permission.INTERNET" />