File Download 1. Download file Business Class
The operation to download the file is also a business method, so create a class in Com.liuhao.mobilesafe.engine that Downloadfiletask download the file.
The GetFile method, which downloads files from the server file path to the local file directory.
Package Com.liuhao.mobilesafe.engine;import Java.io.file;import Java.io.fileoutputstream;import Java.io.inputstream;import Java.net.httpurlconnection;import Java.net.url;public class DownloadFileTask {/** * @pa RAM Path * Server file path * @param filepath * Local file path * @return This section file object * @throws Excepti On */public static File GetFile (string path, string filepath) throws Exception {URL url = new URL (path); HttpURLConnection conn = (httpurlconnection) url.openconnection (); Conn.setrequestmethod ("GET"); Conn.setreadtimeout (5000); Read data without exception if (conn.getresponsecode () = =) {InputStream is = Conn.getinputstream ();//get file input stream File File = new file (filepath);//FileOutputStream FOS = new FileOutputStream (file);//local file output stream byte[] buffer = new byte[1024]; int length = 0; while (length = is.read (buffer))! =-1) {Fos.writE (buffer, 0, length); } fos.flush (); Fos.close (); Is.close (); return file; } return null; }}2. Use the download file class
After the user clicks "OK", the download will be done.
A progress bar is defined to show the download process:
Private ProgressDialog pd;//progress bar PD = new ProgressDialog (this);pd. Setmessage ("Downloading, please be patient." O (∩_∩) o ");//Set the content displayed by the progress bar Builder.setpositivebutton (" OK ", new Onclicklistener () {//Set the key operation when the user chooses to determine @Over Ride public void OnClick (Dialoginterface dialog, int which) {log.i (TAG, "Download Pak text Items: "+ info.getapkurl ()); Determine if the SD card is available if (Environment.getexternalstoragestate (). Equals (environment.media_mounted)) { Calling a child thread to download downloadfilethreadtask task = new D Ownloadfilethreadtask (Info.getapkurl (), Environment.getexternalstoragedirectory (). Getp Ath () + "/aanew.apk"); Pd.show ();//Displays the download progress bar new Thread (Task). Start ();//start child thread} else { Toast.maketext (Getapplicationcontext (),"SD card not available", Toast.length_long). Show (); Loadmainui (); } } }); Sub-thread for downloading files because the download file is time consuming private class Downloadfilethreadtask implements Runnable {private String path;//server path Private String filepath;//Local file path public downloadfilethreadtask (string path, string filepath) { This.path = path; This.filepath = filepath; } @Override public void Run () {try {File file = Downloadfiletask.getfile (path, F Ilepath); LOG.I (TAG, "Download update apk success"); Pd.dismiss (); } catch (Exception e) {e.printstacktrace (); Toast.maketext (Getapplicationcontext (), "Download file failed", Toast.length_long). Show (); Pd.dismiss (); Loadmainui (); } } }3. Add Permissions
Because the download file needs to read and write to the SD card, inherited need the SD card permission: <uses-permission android:name= "Android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/ >
Write permissions for external storage devices: <uses-permission android:name= "Android.permission.WRITE_EXTERNAL_STORAGE"/>
4. Configure the server-side APK file (high version)
Change the current version number to 2.0, generate an APK installation package, put it in the previously specified directory (%tomcat_home%\webapps\root), and then change it back.
Exception handling:
Error/androidruntime (1540): caused By:android.view.windowmanager$badtokenexception:unable to add window--Token null I s not for an application
Our child activity in Activitygroup or tabactivity creates dialog if the following code is used
ProgressDialog = new ProgressDialog (xxx.this)
The following exception will appear when creating:
Error/androidruntime (6362): android.view.windowmanager$badtokenexception:unable to add window-Token [email Protected] is not valid; Is your activity running?
and the use:
ProgressDialog = new ProgressDialog (GetParent ())
Cause Analysis:
Since the new dialog box, the content of the parameter is specified as this, which is the content that points to the current child activity. However, the child activity is created dynamically and cannot be guaranteed to persist. The content of the parent activity is stable, so there is a workaround.
If nested activitygroup in Activitygroup, how many getparent () should be used.
Why use GetParent? We can understand from the internal mechanism of Activitygroup in the tenth chapter of "AMS Internal principle" in "Android Kernel Anatomy" of New Year's Day:
The parent class of Tabactivity is Activitygroup, and Activitygroup's parent class is activity. So from the AMS point of view, activitygroup and ordinary activity is no different, its life cycle includes the standard Start,stop,resume,destroy and so on, Moreover, only one activitygroup is allowed in the system. But there is an important member variable inside the Activitygroup, which is of type Localactivitymanager, and the greatest feature of this class is that it can access the main class of the application process. That is, the Activitythread class. When AMs starts an activity or endorses an activity that is performed through the Activitythread class, the Localactivitymanager class means that it can be used to load different activity. and control the different states of the activity. Note that this is the load, not the start, which is important. The so-called startup, generally refers to the creation of a process (if the application is often not present) to run the activity, and the load simply refers to the activity as a normal class to load, and create a class of the object, and any function of the class is not run. The process of loading activity objects is completely invisible to AMS, and the embedded activity only contributes to the window windows that it contains. The different states of the child activity are handled by Movetostate.
So the child activity is not like normal activity, it just provides window, so when creating dialog, you should use GetParent to get activitygroup real activity, Before adding dialog to the activity.
Reference:
http://aijiawang-126-com.iteye.com/blog/1717368
After the download deployment is complete, the effect
File installation (automatically installed after download is complete) (Knowledge point: Intent)
/*** Install apk file * @param file*/private void Install (file file) { Intent Intent = new Intent (); Intent.setaction (Intent.action_view); Intent.setdataandtype (uri.fromfile (file), "application/vnd.android.package-archive"); Finish ();//End Current Activity
Let the current activity delay 2 seconds to determine if updates are needed (Knowledge point: Handler)
Private String versiontext;private Handler Handler = new Handler () { @Override public void Handlemessage (Message msg) { super.handlemessage (msg); if (Isneedupdate (Versiontext)) { log.i (TAG, "popup Upgrade Dialog"); Showupdatedialog (); }
In the OnCreate method:
Let the current activity delay for two seconds before checking for update new Thread () {public void run () { try { sleep ( )}; Handler.sendemptymessage (0);//Send an empty message to the main thread } catch (Interruptedexception e) { e.printstacktrace (); }
Set download progress bar to show download progress (Knowledge point: ProgressDialog)
Add a progressdialog as a parameter in the GetFile () method of the download task class Downloadfiletask to set it up during the download.
/*** @param path* Server file path * @param filepath* local file path * @param pd* progress bar to show download progress * @return The object * @throws exception*/public static file GetFile (string path, string filepath, ProgressDialog PD) throws Exception { URL url = new URL (path); HttpURLConnection conn = (httpurlconnection) url.openconnection (); Conn.setrequestmethod ("GET"); Conn.setreadtimeout (5000); Read data without exception if (conn.getresponsecode () = =) {int total = Conn.getcontentlength ();//Gets the overall length of the content Pd.setma X (total); InputStream is = Conn.getinputstream ();//Gets the file input stream of the filename file = new file (filepath);//local file Object FileOutputStream FOS = new FileOutputStream (file);//local output stream byte[] buffer = new byte[1024]; int length = 0; int process = 0;//current progress while (length = is.read (buffer))! =-1) {fos.write (buffer, 0, length); Process + = length; Pd.setprogress (process);//Set Current Progress Thread.Sleep (50); } fos.flush (); Fos.close (); Is.close (); return file; } return null;
Because the default progressdialog does not show the download progress, it needs to be set.
Pd.setprogressstyle (progressdialog.style_horizontal);//The progress is not shown by default, this setting is used to show progress
Effect:
"While doing project learning Android" Mobile security defender 04_02: Download and install a new version of the installation package from the server