Re-connect Downloadprovider after network disconnect continue download issue

Source: Internet
Author: User

Recently encountered a disconnect WiFi after disconnecting Wi-Fi on Android 4.4, downloadprovider continue to download the file failed issue. Then began to understand the download Management module's breakpoint renewal function: 1, first, analyze the Android log, when the network is disconnected, the download will abort, the following message appears: W/downloadmanager (29473): Aborting request for Download 5:failed reading Response:java.net.SocketException:recvfrom failed:etimedout (Connection timed out) I/downloa Dmanager (29473): Download 5 finished with status Waiting_for_network search the code for failed reading response, Discovery is the exception that is thrown when the network data stream is constantly being read in the download data:/** * Transfer as much data as possible from the HTTP response to the * destination file. */private void TransferData (state-state, InputStream-in, OutputStream-out) throws Stoprequestexception {final byte data[ ] = new Byte[constants.buffer_size]; for (;;) {int bytesread = Readfromresponse (state, data, in); if (bytesread = =-1) {//success, end of stream already reached hand Leendofstream (state); Return } State.mgotdata = true; Writedatatodestination (state, data, bytesread, out); State.mcurrentbytes + = Bytesread; ReportProgress (state); Checkpausedorcanceled (state); } read the network in the loop.Side response, when the network is disconnected, the InputStream read interface should throw an exception, the code to catch, and determine if the breakpoint can be resumed, and then throw the corresponding message:/** * Read some data from the HTTP response stream, Handling I/O errors. * @param data buffer to use to read data * @param entitystream stream for reading the HTTP response entity * @return The N Umber of bytes Actually read or-1 if the end of the stream has been reached */private int readfromresponse (state State, byte[] data, InputStream Entitystream) throws Stoprequestexception {try {return entitystream.read (data);} catch (Ioexce Ption ex) {contentvalues values = new Contentvalues (); Values.put (Downloads.Impl.COLUMN_CURRENT_BYTES, State.mcurrentbytes); Mcontext.getcontentresolver (). Update (Minfo.getalldownloadsuri (), values, NULL, NULL); if (Cannotresume (state)) {throw new Stoprequestexception (Status_cannot_resume, "Failed reading response:" + ex + "; Unable to resume ", ex); } else {throw new stoprequestexception (Status_http_data_error, "Failed reading response:" + ex, Ex);}}} Whether the judgment here can be renewed, there are many conditions, mainly two aspects, download the wordWhether the number of sections is greater than 0 or whether the DRM download requires conversion: D/downloadmanager (9658): state.mcurrentbytes=5257536 state.mheaderetag= 69b8155f8ae29636cec71afb21637c92 Minfo.mnointegrity=false state.mmimetype=application/ Vnd.android.package-archive Export the database and view the download management file status at this time: How does this state status = 195 come from? We can continue to follow the code, said before, when the network is disconnected, the code starts to throw an exception stoprequestexception, and with the error code, carefully read the code, this exception is the various methods, layer by layer on the net, and finally reached the download management thread Downloadthread Class, it also prints the log message after the exception is catch, and adds processing: catch (stoprequestexception error) {//Remove the cause before printing, in CAs E it contains PII errormsg = Error.getmessage (); String msg = "Aborting request for download" + Minfo.mid + ":" + errormsg; LOG.W (Constants.tag, msg); if (CONSTANTS.LOGV) {LOG.W (Constants.tag, MSG, error);} FinalStatus = Error.getfinalstatus (); It can be seen from the code that it increases the ID information that the download file holds in the database, and then adds a new message to the error, as well as the Log:w/downloadmanager (29473) that we finally see: Aborting Request for download 5: Failed reading Response:java.net.SocketException:recvfrom failed:etimedout (Connection timed out) after outputting the information, It will process the error code judgment, want to break the network this problem, there will be a continuation of the attempt, and then determine the final error code. MostThe error code that initially throws the exception is Status_http_data_error, which is 495. W/downloadmanager (11584): Aborting request for download 5:failed reading Response:java.net.SocketException:recvfrom FA Iled:etimedout (Connection timed out) D/downloadmanager (11584):-----finalstatus=495 Last code conversion://Some errors should be re Tryable, unless we fail too many times. if (isstatusretryable (FinalStatus)) {if (state.mgotdata) {numfailed = 1;} else {numfailed + = 1;} if (Numfailed < C Onstants. Max_retries) {Final Networkinfo info = msystemfacade.getactivenetworkinfo (minfo.muid); if (info! = NULL && INFO.G Ettype () = = State.mnetworktype && info.isconnected ()) {//underlying network is still intact, use normal Backoff FinalStatus = Status_waiting_to_retry; } else {//Network changed, retry on any next available finalstatus = Status_waiting_for_network;}} } will become status_waiting_for_network 195 and then processed in finally, by notifying the method notifydownloadcompleted to store the state value in the database, that is, we finally see the status = 195 the need for conversion, I think is the lowest level of the error code is defined by the HTTP network, and we stored in the database of the shapeThe value of the configuration is for the Download management module, the definition and use of the level of detail is different, because the management way. --------------------------------------------------------------------------------------------------------------- ----------------------------2, Network re-connected log information analysis: I/downloadmanager (11584): Download 5 startingstate.mrequesturi=http:/ /w.gdown.baidu.com/data/wisegame/8ae29636cec71afb/17173shouyou_3300.apk?f=m1101i/downloadmanager (11584): Has Run thread before for Id:5, and State.mfilename:/storage/emulated/0/download/17173shouyou_3300.apki/downloadmanager ( 11584): Resuming download for Id:5, and State.mfilename:/storage/emulated/0/download/17173shouyou_3300.apki/ Downloadmanager (11584): Resuming download for Id:5, and starting with file of Length:5367618i/downloadmanager (11584): RE suming download for Id:5, state.mcurrentbytes:5367618, and setting Mcontinuingdownload to True:d/downloadmanager (11584) : useragent:androiddownloadmanager/4.4.2 (Linux; U Android 4.4.2; a11w build/kot49h) D/downloadmanager (11584): Mmimetype =application/vnd.android.package-archive, Mispublicapi=truei/downloadmanager (11584): Download 5 finished with status Successd/downloadmanager (11584): Drm:requestscanfile:info.mfilename=/storage/emulated/0/download/17173shouyou_3300.apk mimeType= application/ Vnd.android.package-archivedownloadreceiver will listen for changes in the network, and when the network is reconnected, it will restart the Download Management service: Else if (action.equals ( Connectivitymanager.connectivity_action) {final Connectivitymanager Connmanager = (connectivitymanager) context. Getsystemservice (Context.connectivity_service); Final Networkinfo info = Connmanager.getactivenetworkinfo (); if (info! = null && info.isconnected ()) {StartService (context);} This time in the implementation of download executedownload, check whether the file has been downloaded to play a role, that is, resuming download that section of the log information, will be the region file path, has downloaded the size and so on information. However, it is important to note that the return code obtained from the network side is not normally HTTP_OK 200: final int responsecode = Conn.getresponsecode (); LOG.I (Constants.tag, "-----[executedownload] responsecode=" +responsecode); I/downloadmanager (11584):-----[executedownload] responsecode=206 through the log information we can see that at this time the return is Http_partial 206, compared to two cases:Case Http_ok:if (state.mcontinuingdownload) {throw new Stoprequestexception (Status_cannot_resume, "Expected partial, B UT received OK "); } processresponseheaders (State, Conn); TransferData (State, Conn); Return Case Http_partial:if (!state.mcontinuingdownload) {throw new Stoprequestexception (Status_cannot_resume, "Expected OK, But received partial "); } transferdata (State, Conn); return; You can see that the latter no longer needs to re-process the header information, just transfer the data directly. The log information above is the case when the network is disconnected and the file is successfully downloaded. --------------------------------------------------------------------------------------------------------------- --------------3, re-open wifi after download failure: I/downloadmanager (11584): Download 6 startingstate.mrequesturi=http:// W.gdown.baidu.com/data/wisegame/32ef8e3c0291add2/baidunuomi_153.apk?f=m1101i/downloadmanager (11584): Has run Thread before for Id:6, and State.mfilename:/storage/emulated/0/download/baidunuomi_153.apki/downloadmanager (11584) : Resuming download for Id:6, and State.mfilename:/storage/emulated/0/download/baidunuomi_153.apki/doWnloadmanager (11584): Resuming download for Id:6, and starting with file of Length:3128774i/downloadmanager (11584): ResU Ming download for Id:6, state.mcurrentbytes:3128774, and setting Mcontinuingdownload to True:d/downloadmanager (11584): U seragent:androiddownloadmanager/4.4.2 (Linux; U Android 4.4.2; a11w build/kot49h) I/downloadmanager (11584):-----[executedownload] Responsecode=200w/downloadmanager (11584): Aborting request for download 6:expected partial, but received Okd/downloadmanager (11584): Mmimetype =application/vnd.an Droid.package-archive, Mispublicapi=truei/downloadmanager (11584): Download 6 finished with status Cannot_ Resume from the key information aborting request for download 6:expected partial, but received OK can be seen, after restarting the download, the return code from the network beyond the normal download is different, the normal situation returns 206, and here the information return code is 200, and then the code throws an exception, that is, from the information can be seen, the code expects to get the return value is not partial, but actually get OK. On the Internet to inquire about the return code information http: HTTP protocol status code is mainly divided into five categories, in general: ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 1xx reserved 2xx indicates that the request successfully received 3xx to complete the request customer needs further refinement of the request 4XX Customer Error 5XX Server error continue indicates that the client shouldThe request continues. Loopback is used to notify the client that this request has been received and is not rejected by the server. The client should continue to send the remaining request data, or the request has been completed, or the loopback data is ignored. The server must send the final loopback after the request. 101 Switching Protocols server according to customer service request, through the upgrade header information, change the current connection application protocol. The server will immediately change the protocol according to the upgrade header at the end of the 101 send-back with a blank line. Successful =================================200 OK indicates that the client's request has been successfully received, resolved, accepted. 201 Created The request has been completed and a new return resource is created. The resource that is created may be a URI resource, usually a URI resource specified in the location header. Loopback should contain an Entity data and include resource attributes and location to select the appropriate method through the user or user agent. The Entity Data format specifies the Content-type head by the coal type. The first server must create the specified resource before returning the 201 status code. If the behavior is not executed immediately, the server should return 202. 202 Accepted request has been accepted for processing. But the processing did not complete. The request might or may not have been followed because the processing might have been rejected during the actual execution. 203 non-authoritative Information204 No Content server has accepted the request and it is not necessary to return the Entity data, you may need to return the update information. The loopback may contain new or updated information that is rendered by entity-headers. 205 the Reset Content server has accepted the request and the user agent should reset the document view. 206 Partial Content Server has accepted the request for GET Request Resources section. The request must contain a range header information to indicate that the fetch scope may have to contain the If-range header information to form the request condition. Redirection ==================================300 multiple choices requests that resources conform to any one of the rendering methods. 301 Moved Permanently The requested resource has been assigned a new URI. 302 Found A temporary file that requests resources through different URIs. 303 See Other304 not Modified if the client has completed a conditional request and the request is allowed, but the document does not change, the server should return a 304 status code. 304 StatusThe code must not contain the information body, which usually ends with the first empty line after a header field. The resource requested by the 305 use proxy must be accessed through the proxy (specified by the Location field). The location resource gives the URI of the proxy. 306 Unused307 Temporary Redirect Client error =====================400 Bad request because the incorrect syntax causes the server to not understand the requested information. 401 Unauthorized If the request requires user authentication. The loopback should contain a Www-authenticate header field that indicates the permission to request the resource. 402 Payment Required reserved Status code 403 The Forbidden server accepted the request, but was denied processing. 404 Not Found Server has found any resources that match Request-uri. 405 Menthod not allowed Request-line The requested method is not allowed through the specified URI. 406 Not Acceptable407 proxy authentication Required408 reqeust Timeout client did not submit any requests within the server waiting processing time. 409 Conflict410 Gone411 Length Required The server refuses to accept the request without defining the Content-length field. 412 Precondition Failed413 Request Entity Too Large The server refuses to process the request because the request data exceeds the range that the server can handle. The server may close the current connection to prevent the client from continuing the request. 414 Request-uri Too Long Server denial of service current request because the length of the URI exceeds the resolution range of the server. 415 Unsupported Media Type server denies the service current request because the request data format is not supported by the requested resource. 416 Request Range not Satisfialbe417 expectation Failed Server Error ===================================500 Internal Serv The ER Error server encounters an exception that prevents the execution of the current request 501 not implemented the server does not have an appropriate execution action to complete the current request. 502 Bad Gateway503 Service Unavailable The server cannot process the current request because of a temporary file overload. 504 Gateway Timeout505 Http Version not supported from the above information to guess 206 is the previous request, the next request for the rest of the content, download management sent out the request information should be consistent with the normal download. Careful testing found that, from the settings directly after the WiFi, and not really connected, or need to login and enter the password, this may be related to the router settings. This type of exception is handled in the code as described above, the upper layer is captured, then processed, and the state value is eventually stored in the database: throw new Stoprequestexception (Status_cannot_resume, "expected partial, But received OK "); This problem should not be considered a downloadprovider problem, because there is no connection on the network, so the resulting return value is faulty, resulting in the final download failure, because the download management has been defined in this case is not able to continue to load. --------------------------------------------------------------------------------------------------------------- ---------------------------------4, another analysis is the download midway through the network, the notification bar download progress display will also be swept away, before the project manager thought there is a problem, should be retained as a download paused state. I didn't know about the features of download management before, so I went on to look at the code. Notification bar update is mainly through Mnotifier, that is, the processing in class Downloadnotifier, in the download service updatelocked, by obtaining the current download byte information in the database to update the progress of the notification bar://update Notifications visible to User Mnotifier.updatewith (Mdownloads.values ()); private static final int type_active = 1; private static final int type_waiting = 2; private static final int type_complete = 3; Notification bar information is divided into the above three categories,Downloading, waiting for download, download complete. Each time the notification bar is updated, the information for each download file in the database is built with a tag:/** * build tag used for collapsing several {@link downloadinfo} to a single * {@link Notification}. */private static String Buildnotificationtag (Downloadinfo info) {if (Info.mstatus = = Downloads.Impl.STATUS_QUEUED_FOR_ WIFI) {return type_waiting + ":" + info.mpackage;} else if (isactiveandvisible (info)) {return type_active + ":" + info.mpackage;} else if (iscompleteandvisible (info)) {//downloads always has a unique notifs return type_complete + ":" + INFO.M Id; } else {return null;}} The re-built process database has a field of information that is also used, that is, the visibility property: There are only two cases of type type_active and Type_complete in my debugging. In the final processing of the update notification bar, there is a piece of code to clean up some of the notification information, including the type of download interruption://Remove stale tags that weren ' t renewed final Iterator it = Mactivenotifs.keyset (). iterator (); while (It.hasnext ()) {final string tag = It.next (); if (!clustered.con Tainskey (tag)) {//not included in the tag list, need to clear mnotifmanager.cancel (tag, 0); It.remove ();}} Log information, build a good tag form is type:id, of course, this is already downloaded completed: D/downloadmanager (32155): =====tag=3:15d/downloadmanager (32155): =====tag= 3:14d/downloadmanager (32155): =====tag=3:13d/downloadmanager (32155): =====tag=3:12d/downloadmanager (32155): ===== Tag=3:6d/downloadmanager (32155): =====tag=3:19d/downloadmanager (32155): =====tag=3:18d/downloadmanager (32155): = = ===tag=3:17d/downloadmanager (32155): =====tag=3:16d/downloadmanager (32155): =====tag=3:20d/downloadmanager (32155 ): =====tag=3:11d/downloadmanager (32155): =====tag=3:10d/downloadmanager (32155): =====tag=3:21d/downloadmanager ( 32155): =====tag=1:com.android.browserd/downloadmanager (32155): =====remove tag=1: Com.android.browser and that's the sort of thing. After a key cleanup, the update information is no longer displayed in the notification bar because its tag is null and is not included in the tag list.

Re-connect Downloadprovider after network disconnect continue downloading problems

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.