Easy Tutorial
❮ Verilog2 Sdf Cpp Func Setw ❯

7.3.2 Android File Download (1)

Category Android Basic Tutorial

Introduction of This Section:

>


1. Standard Single-threaded File Download:

>

Directly use URLConnection.openStream() to open a network input stream, and then write the stream into a file!

Core Method :

public static void downLoad(String path,Context context)throws Exception
{
  URL url = new URL(path);
  InputStream is = url.openStream();
  //Extract the file name at the end
  String end = path.substring(path.lastIndexOf("."));
  //Open the corresponding output stream on the phone and write to the file
  OutputStream os = context.openFileOutput("Cache_"+System.currentTimeMillis()+end, Context.MODE_PRIVATE);
  byte[] buffer = new byte[1024];
  int len = 0;
  //Read data from the input stream into the buffer
  while((len = is.read(buffer)) > 0)
  {
    os.write(buffer,0,len);
  }
  //Close input and output streams
  is.close();
  os.close();
}

Running Result :


2. Standard Multi-threaded Download:

We all know that downloading files using multi-threading can complete the download faster, but why is that?

>

Answer: Because it seizes more server resources. Suppose the server can serve up to 100 users, and one thread in the server corresponds to 100 threads in the computer that are executed concurrently, with the CPU allocating time slices for them to take turns. If 'a' has 99 threads downloading files, it is equivalent to occupying the resources of 99 users, and naturally, the download speed is faster.

PS : Of course, more threads are not always better. Starting too many threads can lead to increased overhead for the app to maintain and synchronize each thread, which can actually reduce the download speed. It also depends on your internet speed!

Multi-threaded download process :

>

PS: Here, just create a Java project and then run the specified method in JUnit.

Core code as follows :

``` public class Downloader { //Adding the @Test tag indicates that this method is a JUnit test method, which can be run directly @Test public void download() throws Exception { //Set the URL address and the file name after download String filename = "meitu.exe"; String path = "http://10.13.20.32:8080/Test/XiuXiu_Green.exe"; URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(5000); conn.setRequestMethod("GET"); //Get the length (size) of the file to be downloaded int filelength = conn.getContentLength(); System.out.println("The length of the file to be downloaded is " + filelength); //Generate a local file of the same size RandomAccessFile file = new RandomAccessFile(filename, "rwd"); file.setLength(filelength); file.close(); conn.disconnect(); //Set the number of threads to download int threadsize = 3; //Calculate the amount each thread needs to download int threadlength = filelength % 3 == 0 ? filelength / 3 : filelength + 1; for(int i = 0; i < threadsize; i++) { //Set the starting position for each thread to download int startposition = i * threadlength; //From which position in the file to start writing data RandomAccessFile threadfile = new RandomAccessFile(filename, "rwd"); threadfile.seek(startposition); //Start three threads to download the file from the startposition position new DownLoadThread(i, startposition, threadfile, threadlength, path).start(); } int quit = System.in.read(); while('q' != quit) { Thread.sleep(2000); } }

private class DownLoadThread extends Thread { private int threadid; private int startposition; private RandomAccessFile threadfile; private int threadlength; private String path; public DownLoadThread(int threadid, int startposition, RandomAccessFile threadfile, int threadlength, String path) { this.threadid = threadid; this.startposition = startposition; this.threadfile = threadfile; this.threadlength import android.support.v7.app.AppCompatActivity;

/**

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    String endpoint = "";
    try {
        //This part is to obtain configuration information from AndroidManifest.xml, package name, and things saved in Meta_data
        ApplicationInfo info = getPackageManager().getApplicationInfo(
                getPackageName(), PackageManager.GET_META_DATA);
        //We saved a data of xxx.xxx in meta_data, which is a link starting with https, replace it with http here
        endpoint = info.metaData.getString("xxxx.xxxx").replace("https",
                "http");
    } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
    }
    //The following are all about splicing the URL for downloading the APK update, path is the saved folder path
    final String _Path = this.getIntent().getStringExtra("path");
    final String _Url = endpoint + _Path;
    final DownloadManager _DownloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
    DownloadManager.Request _Request = new DownloadManager.Request(
            Uri.parse(_Url));
    _Request.setDestinationInExternalPublicDir(
            Environment.DIRECTORY_DOWNLOADS, FILE_NAME + ".apk");
    _Request.setTitle(this.getString(R.string.app_name));
    //Whether to show the download dialog box
    _Request.setShowRunningNotification(true);
    _Request.setMimeType("application/com.trinea.download.file");
    //Put the download request into the queue
    _DownloadManager.enqueue(_Request);
    this.finish();
}

//Register a broadcast receiver, after the download is completed, a broadcast of android.intent.action.DOWNLOAD_COMPLETE
//will be received, and the download task in the queue will be taken out and installed here
public static class Receiver extends BroadcastReceiver {
    public void onReceive(Context context, Intent intent) {
        final DownloadManager _DownloadManager = (DownloadManager) context
                .getSystemService(Context.DOWNLOAD_SERVICE);
        final long _DownloadId = intent.getLongExtra(
                DownloadManager.EXTRA_DOWNLOAD_ID, 0);
        final DownloadManager.Query _Query = new DownloadManager.Query();
        _Query.setFilterById(_DownloadId);
        final Cursor _Cursor = _DownloadManager.query(_Query);
        if (_Cursor.moveToFirst()) {
            final int _Status = _Cursor.getInt(_Cursor
                    .getColumnIndexOrThrow(DownloadManager.COLUMN_STATUS));
            final String _Name = _Cursor.getString(_Cursor
                    .getColumnIndexOrThrow("local_filename"));
            if (_Status == DownloadManager.STATUS_SUCCESSFUL
                    && _Name.indexOf(FILE_NAME) != 0) {

                Intent _Intent = new Intent(Intent.ACTION_VIEW);
                _Intent.setDataAndType(
                        Uri.parse(_Cursor.getString(_Cursor
                                .getColumnIndexOrThrow(DownloadManager.COLUMN_LOCAL_URI))),
                        "application/vnd.android.package-archive");
                _Intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(_Intent);
            }
        }
        _Cursor.close();
    }
}

}

4. Reference code download:

Normal single-threaded file download: DownLoadDemo1.zip Normal multi-threaded file download: J2SEMulDownLoader.zip


Summary of this section:

>

Well, this section introduced everyone to normal single-threaded and multi-threaded file downloads, as well as using Android's built-in DownManager to download and update APKs, and then implement the overlay! I believe it will bring convenience to everyone's actual development, well, that's all, thank you~

-1.0 Android Basic Tutorial

-1.0.1 Latest Android Basic Tutorial Catalog for 2015

-1.1 Background and System Architecture Analysis

-1.2 Development Environment Construction

-1.2.1 Developing Android APP with Eclipse + ADT + SDK

-1.2.2 Developing Android APP with Android Studio

-1.3 Solving SDK Update Issues

-[1.4 Genymotion Emulator Installation](android-tutorial-genymotion-install.html

❮ Verilog2 Sdf Cpp Func Setw ❯