F-droid source code snippet (2) download module arrangement, f-droid source code

Source: Internet
Author: User

F-droid source code snippet (2) download module arrangement, f-droid source code

In this article, the download function of F-droid is modified separately and a demo is provided.

It is hoped that it will serve as a reference for the future. You can also download the kids shoes.

 

In fact, there are two main ideas:

 

1. Use interfaces for callback

2. The thread calls the callback directly. Because the main thread cannot know whether to perform UI operations, the callback of the thread is encapsulated and sent by Handler. It will not crash.

 

 

Project:

Http://download.csdn.net/download/leehu1987/7979253

 

1. Define an interface for monitoring the page download status;

<pre class="java" name="code">import java.io.Serializable;public interface DownloadListener {public static class Data implements Serializable {private static final long serialVersionUID = 8954447444334039739L;private long currentSize;private long totalSize;public Data() {}public Data(int currentSize, int totalSize) {this.currentSize = currentSize;this.totalSize = totalSize;}public long getCurrentSize() {return currentSize;}public void setCurrentSize(long currentSize) {this.currentSize = currentSize;}public long getTotalSize() {return totalSize;}public void setTotalSize(long totalSize) {this.totalSize = totalSize;}@Overridepublic String toString() {return "Data [currentSize=" + currentSize + ", totalSize="+ totalSize + "]";}}/** *  * @param data *            : transfer downloaded data */public void onProgress(Data data);/** *  * @param e *            : exception */public void onError(Exception e);public void onCompleted();}
 

 

2. defines a Downloader parent class. In order to adapt to different downloads, such as using Http for download and using a proxy for download.

Therefore, this class is an interface class that defines some basic operation methods.

 

Package com. example. downloader;

package com.example.downloader;import java.io.File;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.net.MalformedURLException;import java.net.URL;import android.util.Log;public abstract class Downloader {private static final String TAG = "Downloader";protected URL sourceUrl;private OutputStream outputStream;private DownloadListener downloadListener = null;private File outputFile;private final int BUFFER_SIZE = 1240000;//1M// ///////////////////////////public abstract InputStream getInputStream() throws IOException;public abstract int totalDownloadSize();public abstract void download() throws IOException, InterruptedException;// ///////////////////////////Downloader(File destFile) throws FileNotFoundException,MalformedURLException {outputFile = destFile;outputStream = new FileOutputStream(outputFile);}public void setProgressListener(DownloadListener downloadListener) {this.downloadListener = downloadListener;}public File getFile() {return outputFile;}protected void downloadFromStream() throws IOException,InterruptedException {Log.d(TAG, "Downloading from stream");InputStream input = null;try {input = getInputStream();throwExceptionIfInterrupted();copyInputToOutputStream(getInputStream());} finally {try {if (outputStream != null) {outputStream.close();}if (input != null) {input.close();}} catch (IOException ioe) {// ignore}}// Even if we have completely downloaded the file, we should probably// respect// the wishes of the user who wanted to cancel us.throwExceptionIfInterrupted();}/** * stop thread *  * @throws InterruptedException */private void throwExceptionIfInterrupted() throws InterruptedException {if (Thread.interrupted()) {Log.d(TAG, "Received interrupt, cancelling download");throw new InterruptedException();}}protected void copyInputToOutputStream(InputStream input)throws IOException, InterruptedException {byte[] buffer = new byte[BUFFER_SIZE];int bytesRead = 0;int totalBytes = totalDownloadSize();throwExceptionIfInterrupted();sendProgress(bytesRead, totalBytes);while (true) {int count = input.read(buffer);throwExceptionIfInterrupted();bytesRead += count;sendProgress(bytesRead, totalBytes);if (count == -1) {Log.d(TAG, "Finished downloading from stream");break;}outputStream.write(buffer, 0, count);}outputStream.flush();}protected void sendProgress(int bytesRead, int totalBytes) {if (downloadListener != null) {DownloadListener.Data data = new DownloadListener.Data(bytesRead,totalBytes);downloadListener.onProgress(data);}}}

 

3. Write an HttpDownloader. Inherited from Downloader

package com.example.downloader;import java.io.File;import java.io.FileNotFoundException;import java.io.IOException;import java.io.InputStream;import java.net.HttpURLConnection;import java.net.MalformedURLException;import java.net.URL;public class HttpDownloader extends Downloader {protected HttpURLConnection connection;HttpDownloader(String source, File destFile) throws FileNotFoundException,MalformedURLException {super(destFile);sourceUrl = new URL(source);}@Overridepublic void download() throws IOException, InterruptedException {setupConnection();downloadFromStream();}protected void setupConnection() throws IOException {if (connection != null) {return;}connection = (HttpURLConnection) sourceUrl.openConnection();}@Override    public InputStream getInputStream() throws IOException {        setupConnection();        return connection.getInputStream();    }@Override    public int totalDownloadSize() {        return connection.getContentLength();    }}



4. A control method is required.

 

Package com. example. downloader; import java. io. IOException; import com. example. downloader. downloadListener. data; import android. OS. handler; import android. OS. message; import android. util. log; public class DownloadManager extends Handler {private DownloadThread downloadThread; private Downloader downloader; private DownloadListener listener; private static final int MSG_PROGRESS = 1; private static final int MSG_DOWNLOAD_COMPLETE = 2; private static final int MSG_DOWNLOAD_CANCELLED = 3; private static final int MSG_ERROR = 4; public DownloadManager (Downloader downloader, DownloadListener listener) {this. downloader = downloader; this. listener = listener;} @ Overridepublic void handleMessage (Message msg) {super. handleMessage (msg); switch (msg. what) {case MSG_PROGRESS: {DownloadListener. data data = (Data) msg. o Bj; if (listener! = Null) {listener. onProgress (data);} break;} case MSG_DOWNLOAD_COMPLETE: {if (listener! = Null) {listener. onCompleted () ;} break;} case MSG_DOWNLOAD_CANCELLED: {break;} case MSG_ERROR: {Exception e = (Exception) msg. obj; if (listener! = Null) {listener. onError (e) ;}break;} default: return ;}} public void download () {downloadThread = new DownloadThread (); downloadThread. start ();} private class DownloadThread extends Thread implements <strong> <span style = "color: # ff6666; "> DownloadListener </span> </strong> {private static final String TAG =" DownloadThread "; public void run () {try {downloader. setProgressListener (this); downloader. download (); sendMessage (MSG_DOWNLOAD_COMPLETE);} catch (InterruptedException e) {sendMessage (MSG_DOWNLOAD_CANCELLED);} catch (IOException e) {Log. e (TAG, e. getMessage () + ":" + Log. getStackTraceString (e); Message message = new Message (); message. what = MSG_ERROR; message. obj = e; sendMessage (message) ;}} private void sendMessage (int messageType) {Message message = new Message (); message. what = messageType; DownloadManager. this. sendMessage (message);} private void sendMessage (Message msg) {DownloadManager. this. sendMessage (msg) ;}@ Overridepublic void onProgress (Data data) {// TODOMessage message = new Message (); message. what = MSG_PROGRESS; message. obj = data; DownloadManager. this. sendMessage (message) ;}@ Overridepublic void onError (Exception e) {// There is no use here, the Exception is caught // do nothing }@overridepublic void onCompleted () {// do nothing }}}


5. How to Use pages

<Pre class = "html" name = "code"> package com. example. downloader; import java. io. file; import java. io. fileNotFoundException; import java.net. malformedURLException; import android. OS. bundle; import android. OS. environment; import android. app. activity; import android. view. menu; public class MainActivity extends Activity implements DownloadListener {@ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); String dir = Environment. getExternalStorageDirectory (). getAbsolutePath () + File. separator + "test.apk"; File f = new File (dir); try {Downloader downloader = new HttpDownloader ("http: // 192.168.131.63/fengxing2.2.0.6.apk", f ); downloadManager m = new DownloadManager (downloader, this); m. download ();} catch (FileNotFoundException e) {e. printStackTrace ();} catch (MalformedURLException e) {e. printStackTrace () ;}@ Overridepublic 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;} @ Overridepublic void onProgress (Data data) {System. out. println ("======" + data) ;}@ Overridepublic void onError (Exception e) {System. out. println ("======"); e. printStackTrace () ;}@ Overridepublic void onCompleted () {System. out. println ("====== download complete ");}}

 


Unfinished functions:

1. breakpoint download (database required)

2. If the download is complete, you do not need to download it next time.

 


Easy language super Module source code download

There are 3.65 on the official website of easy language.

How to convert the easy-language source code into a module? I downloaded the source code but want to convert it into a module.

-This question is brilliant...
The
 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.