Android Learning Series (19)-Offline app download

Source: Internet
Author: User

We recommend that you plan for the rain and explore the wells without thirst. ---- Zhu Yichun zhijia Maxim

Offline download: downloads server data in the case of a network, so that you can read data without a network, that is, read data offline.

The offline download function is as follows:
1. Download Management (START and cancel download ).
2. Network judgment (wi-fi, 3G ).
3. Independent process.
4. timed and mobile phone reminders.
5. self-starting.

1. Download Management
Here, we cannot focus on the download details. There are many methods for online download, probably as follows:

/*** Download file ** @ Param URL * @ Param DEST download local file stored in * @ Param append resumable upload * @ return * @ throws exception */public long download (string URL, file DEST, Boolean append) throws exception {// initialization variable // preparation //...... try {//...... while (readsize = is. read (buffer)> 0) {// network judge OS. write (buffer, 0, readsize); OS. flush (); // if you need to stop the download, such as canceling the download, the current download is displayed.} finally {//......} //......}

Note the following points:
(1) During the download process, we hope to detect the network conditions in time. For example, if we switch from Wi-Fi to 3G, we should be able to stop the download in time.
(2). When the user chooses to cancel the download, we can also stop the current download.

2. Network judgment
To obtain the current network status, we mainly divided it into wi-fi and mobile (including 3G, GPRS). We write a tool class as follows:

 public class networkutils {public final static int none = 0; // No network public final static int WiFi = 1; // Wi-Fi public final static int mobile = 2; // 3G, GPRS/*** get the current network status * @ Param context * @ return */public static int getnetworkstate (context) {connectivitymanager connmanager = (connectivitymanager) context. getsystemservice (context. connectivity_service); // determines the state = connmanager on the mobile phone network. getnetworkinfo (connectivitymanager. type_mobile ). getstate (); If (State = state. connected | state = state. connecting) {return mobile;} // WiFi network determines state = connmanager. getnetworkinfo (connectivitymanager. type_wifi ). getstate (); If (State = state. connected | state = state. connecting) {return WiFi;} return none ;}

Based on the network status, we can control the download method:
(1). When downloads are large, we are unlikely to download them in 3G scenarios, which may cause users' dislike and concern.
(2). It is also allowed when the customer confirms that the download can be performed at 3G.
Therefore, we need to set a flexible level for the download method. Based on the characteristics of offline download, we provide three solutions for users:
(1). automatically download Mobile Data
(2). automatically download only when Wi-Fi is allowed
(3). Disable download
Only automatic download is listed here, because if it is not automatic download, you can control the manual download without setting it. Of course, when traffic loss occurs, such as manual download at 3G, prompt that the user will consume a large amount of data traffic, use it with caution.

 
Public class constant {// set public final static int offline_mobile = 0; public final static int offline_wifi = 1; public final static int offline_off = 3 ;} public class global {// set the default off status, // For the applicationProgramThe user can remember the user to choose from the next startup. When the application is started for the first time, this value should eventually be stored in the database. Public static int offlinenetworksetting = constant. offline_off ;}

You can now compare the current network and offline network settings according to the rules to determine whether the offline download service is enabled.

3. Independent Process
Offline download, wherever and whenever appropriate, is performed. Currently, the mainstream approach is to establish background services.

 
Public class offlineserivice extends Service {//......}

(1 ). if the offlineservice process is the same as the application process by default, it will be restarted once when the application process is killed (Netease news will exit the application when downloading offline, the reason is that the download will pause for a while). If the effect is not significant, this solution is optional.
(2 ). the offlineservice process is separated from the application, for example, the application process is "CN. cnblogs. tianxia. download, the offline download service process is set to "CN. cnblogs. tianxia. download. offline ", the relationship between the Process and the application. Of course, this will bring about a new problem: inter-process communication, of course, because offline download and modules between applications are relatively independent, this problem is relatively easy to avoid.
(3 ).If the offlineservice process is consistent with the application by default, but offlineservice inherits the intentservice, restart can be avoided. This is the method mentioned in pro Android 3 and is very easy to use, however, I am very sorry. I recently saw that I have not personally tested it and I am not afraid to try it out at work.
In theory, solution 3 is the best solution, but for personal reasons, solution 2 is selected.

<Manifest xmlns: Android = "http://schemas.android.com/apk/res/android" package = "com. cnblogs. download "> <application Android: icon =" @ drawable/icon "Android: Label =" @ string/app_name ">

  <Service android: Name = "cn. cnblogs. Download. offlineservice" Android: Process = "cn. cnblogs. Download. offline"/> </Application> </manifest>

4. timed download and mobile phone reminders
Automatically downloads are automatically downloaded based on user settings, but there are many automatic download methods, such as frequent update downloads and fixed point downloads (four o'clock P.M ), download interval (every 6 hours ).
Here, we choose to download every six hours.
(1) An incorrect solution is introduced here. Once we see that every six hours, it is easy to think of starting a sub-thread timer, accumulating for six hours, the sub-thread notifies the download service to start a new round of download. The idea of this solution is correct, but it ignores the sleep status of the mobile phone. This sub-thread actually stops running, the so-called 6-hour effect may never be reached, and it must be incorrect or inaccurate.
(2). Therefore, you need to use a non-sleep method: timer and broadcast receiver. We send a broadcast every six hours. The broadcast receiver notification starts offline download. (Refer to the newsrob source code and book "Pro Android 3"):

Public class offlineserivice extends Service {// time when the last download was successful private long lastdownloadtime; // omittedCode...... Public static void startalarm (context) {alarmmanager = (alarmmanager) context. getsystemservice ("alarm"); // send a broadcast to offlinealarmreceiver every six hours. // You can also set it to 10 minutes to check the download conditions. In offlinealarmrecrive, you can determine to start downloading, avoid 6 hours of download failure and wait for 6 hours. Intent intent = new intent (context, offlinealarmreceiver. class); pendingintent = pendingintent. getbroadcast (context. getapplicationcontext (), 0, intent, 0); alarmmanager. cancel (pendingintent); alarmmanager. setrepeating (alarmmanager. rtc_wakeup, system. currenttimemillis (), 3600000*6, pendingintent );}}

In offlinealarmrecriver, process the start download condition and notify the start download:

Public class offlinealarmreceiver extends broadcastreceiver {@ override public void onreceive (context, intent arg1) {// omitting the code ..., initialize the variable and prepare the variable... if (system. currenttimemillis ()-offlineservice. lastdownloadtime> 3600000*60 & other conditions) {// enable the offline download service intent alarmintent = new intent (context, offlineservice. class); context. startservice (alarmintent );}}}

We mentioned the thread sleep problem. We need to wake up the mobile phone during the download process and return to sleep after the download is complete. The following are two tools:

 Public static powermanager. wakelock;/*** wake-up Service */public static void acquirewakelock (context) {If (wakelock! = NULL) {return;} powermanager = (powermanager) (context. getsystemservice (context. power_service); wakelock = powermanager. newwakelock (powermanager. partial_wake_lock, "com. cnblogs. download. offlineservice "); wakelock. acquire ();}/*** release the wake-up service and return the sleep state */public static void releasewakelock () {If (wakelock! = NULL & wakelock. isheld () {wakelock. Release (); wakelock = NULL ;}

WherePowermanager. partial_wake_lock means onlyWake upCPU mode. At this time, the network status can be automatically checked to ensure that the Network is normal.
You need to set the permission in mainifest. xml:

 
<Uses-Permission Android: Name = "android. Permission. wake_lock"/>

Then, enable the reminder status in onstartconmmand () of the download service, and then release the reminder status after the download is complete:

@ Override public int onstartcommand (intent, int flags, int startid) {acquirewakelock (offlineservice. this); // omitting the code ...... return super. onstartcommand (intent, flags, startid );}

5. self-starting
To make the code clearer, we need to define a self-starting aggreger:

 
/*** Automatically start the offline download service * @ author user */public class offlinereceiver extends broadcastreceiver {@ override public void onreceive (context, intent arg1) {// start the timer offlineservice. startalarm (context );}}

Register this receiver in androidmanifest. XML as follows:

<Cycler Android: Name = "cn. cnblogs. Download. offlinereceiver"> <intent-filter> <! -- Auto-start --> <action Android: Name = "android. intent. action. boot_completed "/> <category Android: Name =" android. intent. category. home "/> </intent-filter> </Cycler>

In this way, you can start the broadcast and start the timer at startup.

6. Summary
For simplicity and clarity, this article only lists the most important links for offline downloads. for cleanup policies, manual and automatic modes, and page jumps, uidesign and business requirements are not too much involved, but these things often take a lot of time and require a lot of detail accumulation and patient debugging. The only thing we need to do is to constantly improve!

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.