Android apps are automatically updated and installed

Source: Internet
Author: User

Monitor whether upgrade is required:

PackageManager packageManager = MainActivity.getInstance().getPackageManager();PackageInfo packInfo;try{    packInfo = packageManager.getPackageInfo(MainActivity.getInstance().getPackageName(), 0);    String version = packInfo.versionName;    String serverVersion = NetSend.getInstance().getVersion();    ProjectMacro.apkVersion = version;    if (!serverVersion.equals(version))    {        showUpdataDialog();    }}catch (NameNotFoundException e){   e.printStackTrace();}

Obtain the server version:

public String getVersion(){    String result = null;    URL url = null;    HttpURLConnection connection = null;    InputStreamReader in = null;    try    {       url = new URL(ProjectMacro.URL_VER_COM);       connection = (HttpURLConnection)url.openConnection();       in = new InputStreamReader(connection.getInputStream());       BufferedReader bufferedReader = new BufferedReader(in);       StringBuffer strBuffer = new StringBuffer();       String line = null;       while ((line = bufferedReader.readLine()) != null)       {          strBuffer.append(line);       }       result = strBuffer.toString().trim();       }       catch (Exception e)       {           e.printStackTrace();       }       finally       {          if (connection != null)          {              connection.disconnect();          }          if (in != null)          {              try              {                  in.close();              }              catch (IOException e)              {                  e.printStackTrace();              }          }            }        return result;    }

Download process and automatic installation [divided into: Existing sdcard and existing mobile phone memory]

Private icationicationmanager micationicationmanager; private notification mnotification; Private Static final int handler_message_start_downloading = 0; Private Static final int completion = 1; Private Static final int completion = 2; Private Static final int handler_message_install_complete = 3; private Static final int current_network_error = 10000; private Downloadthread thread = new downloadthread (); Private Boolean isstopdownload; /*** downloadbinder defines some practical methods ** @ author user **/public class downloadthread extends thread {@ override public void run () {super. run (); startdownload () ;}} private handler mupdatehandler = new handler () {public void handlemessage (Message MSG) {Switch (MSG. what) {Case handler_message_start_downloading: setupnot Ification (); break; Case handler_message_is_downloading: setcurrentprogressinfo (MSG. arg1, MSG. arg2); break; Case handler_message_download_complete: setupoknotification (); thread. interrupt (); toast. maketext (mainactivity. getinstance (), "Download complete! ", Toast. length_short). Show (); break; Case handler_message_install_complete: break; Case current_network_error: If (thread! = NULL) {thread. interrupt () ;}showtoast ("network exception", 2); break; default: Break ;}};}; /*** set the current progress ** @ Param currentprogress * @ Param totalsize */private void setcurrentprogressinfo (INT currentprogress, int totalsize) {// update the progress remoteviews contentview = mnotification. contentview; contentview. settextviewtext (R. id. download_file_tempsize, "" + currentprogress + "kb"); contentview. settextviewtext (R. Id. download_file_size, "" + totalsize + "kb"); contentview. setprogressbar (R. id. download_file_progressbar, 100, (INT) (currentprogress * 100/totalsize), false); micationicationmanager. notify (R. string. app_name, mnotification);}/*** Set Download notification */private void setupnotification () {mnotificationmanager = (icationicationmanager) mainactivity. getinstance (). getsystemservice (context. notification_service); mnot Ification = new notification (R. drawable. ic_launcher, "downloading", system. currenttimemillis (); mnotification. flags = notification. flag_ongoing_event; remoteviews Rv = new remoteviews (mainactivity. getinstance (). getpackagename (), R. layout. update_download_apk_progressbar); mnotification. contentview = RV; intent = new intent (); intent. addflags (intent. flag_activity_new_task); pendingintent contentint Ent = pendingintent. getactivity (mainactivity. getinstance (), R. string. app_name, intent, pendingintent. flag_update_current); mnotification. contentintent = contentintent; micationicationmanager. notify (R. string. app_name, mnotification);}/*** download completed */private void setupoknotification () {mnotification. flags = notification. flag_auto_cancel; mnotification. contentview = NULL; file = NULL; If (Environ Ment. getexternalstoragestate (). equals (environment. media_mounted) {// sdcard exists. Upgrade APK to file = new file (environment. getexternalstoragedirectory (), "miq.apk");} else {// sdcard does not exist. Upgrade APK to local storage file = new file (getcachedir (). getabsolutepath () + file. separator + "Download", "miq.apk");} intent = new intent (); intent. setaction (Android. content. intent. action_view); intent. addcategory (inte NT. category_default); intent. setcomponent (New componentname ("com. android. packageinstaller "," com. android. packageinstaller. packageinstalleractivity "); intent. setflags (intent. flag_activity_new_task); intent. setdataandtype (URI. fromfile (file), "application/vnd. android. package-Archive "); startactivity (intent); pendingintent contentintent = pendingintent. getactivity (mainactivity. getinstance (), R. string. App_name, intent, pendingintent. flag_update_current); mnotification. contentintent = contentintent; mnotification. setlatesteventinfo (mainactivity. getinstance (), "download completed", "file downloaded", contentintent); micationicationmanager. notify (R. string. app_name, mnotification);}/*** download module */private void startdownload () {message MSG = mupdatehandler. obtainmessage (); MSG. what = handler_message_start_downloading; MS G. arg1 = 0; mupdatehandler. sendmessage (MSG); httpclient client = new defaulthttpclient (); httpparams = client. getparams (); httpconnectionparams. setconnectiontimeout (httpparams, 1000*60); httpconnectionparams. setsotimeout (httpparams, 1000*60); connmanagerparams. setTimeout (httpparams, 1000*60); httpget get = new httpget (projectmacro. url_down_com); httpresponse response; try {respon Se = client.exe cute (get); httpentity entity = response. getentity (); long length = entity. getcontentlength (); log. I ("downloadnewreceiver", "length is" + length); inputstream is = entity. getcontent (); fileoutputstream = NULL; file = NULL; If (is! = NULL) {If (environment. getexternalstoragestate (). equals (environment. media_mounted) {// The sdcard has file = new file (environment. getexternalstoragedirectory (), "miq.apk");} else {// sdcard does not exist string apkpath = getcachedir (). getabsolutepath () + file. separator + "Download"; string apkname = "miq.apk"; file = new file (apkpath, apkname); If (! File. getparentfile (). exists () {file. getparentfile (). mkdirs () ;}} fileoutputstream = new fileoutputstream (File); byte [] Buf = new byte [2048]; int CH =-1; int COUNT = 0; long starttime = system. currenttimemillis (); While (CH = is. read (BUF ))! =-1) {If (! Netutil. checknet (mainactivity. getinstance () {MSG. what = current_network_error; mupdatehandler. sendmessage (MSG); return;} Long endtime = system. currenttimemillis (); fileoutputstream. write (BUF, 0, CH); count + = CH; // ------ download completion: Send a message notification to handler to update the progress if (isstopdownload! = True) {If (endtime-starttime> 1000) {// one-second update MSG = mupdatehandler. obtainmessage (); MSG. what = handler_message_is_downloading; MSG. arg1 = (count/1024); MSG. arg2 = (INT) (length/1024); mupdatehandler. sendmessage (MSG); starttime = endtime;} isstopdownload = false;} string permission = "755"; // The downloaded folder must have the RX permission (the prerequisite for folder access) string filescom = "chmod" + permission + "" + file. getparentfil E (). getabsolutepath (); // The downloaded object APK must have the X permission, that is, the executable permission, for Android applications, to install string apkcomm = "chmod" + permission + "" + file. getabsolutepath (); // string apkcomm = "chmod-R" + permission + "" + apkpath + "/" // + apkname; // The-r option runtime = Runtime is not supported. getruntime (); runtime.exe C (filescom); runtime.exe C (apkcomm);} fileoutputstream. flush (); If (fileoutputstream! = NULL) {fileoutputstream. Close () ;}// ------ the handler if (isstopdownload! = True) {MSG = mupdatehandler. obtainmessage (); MSG. what = handler_message_download_complete; mupdatehandler. sendmessage (MSG); isstopdownload = false;} Try {thread. sleep (10);} catch (interruptedexception e) {e. printstacktrace () ;}} catch (clientprotocolexception e) {e. printstacktrace ();} catch (ioexception e) {e. printstacktrace () ;}} protected void showupdatadialog () {alertdialog. builder builer = new Builder (mainactivity. getinstance (); builer. settitle ("version upgrade"); builer. setmessage ("the latest version is detected. Please update it in time"); builer. setpositivebutton ("OK", new onclicklistener () {public void onclick (dialoginterface dialog, int which) {thread. start () ;}}); builer. setnegativebutton ("cancel", new onclicklistener () {public void onclick (dialoginterface dialog, int which) {}}); builer. create (); builer. show ();}

Update_download_apk_progressbar.xml

<? XML version = "1.0" encoding = "UTF-8"?> <Linearlayout xmlns: Android = "http://schemas.android.com/apk/res/android" Android: Id = "@ + ID/download_file_progress_layout" Android: layout_width = "match_parent" Android: layout_height = "match_parent" Android: focusable = "true" Android: focusableintouchmode = "true" Android: Orientation = "horizontal"> <imageview Android: layout_width = "wrap_content" Android: layout_height = "wrap_content" Android: layout_gravity = "CEN Ter_vertical "Android: Background =" @ drawable/ic_launcher "/> <linearlayout Android: layout_width =" wrap_content "Android: layout_height =" wrap_content "Android: orientation = "vertical"> <relativelayout Android: layout_width = "wrap_content" Android: layout_height = "wrap_content"> <textview Android: Id = "@ + ID/text" Android: layout_width = "wrap_content" Android: layout_height = "wrap_content" Android: padding = "3dp" Ndroid: text = "download new version" Android: textcolor = "# ffffff" Android: textsize = "16sp"/> <linearlayout Android: id = "@ + ID/downloud_progress_layout" Android: layout_width = "wrap_content" Android: layout_height = "wrap_content" Android: layout_torightof = "@ + ID/text"> <textview Android: id = "@ + ID/download_file_tempsize" Android: layout_width = "wrap_content" Android: layout_height = "wrap_content" Android: padding = "3dp" Android: T EXT = "0 kb" Android: textcolor = "# ffffff"/> <textview Android: layout_width = "wrap_content" Android: layout_height = "wrap_content" Android: layout_marginleft = "3dp" Android: layout_marginright = "3dp" Android: text = "/" Android: textcolor = "# ffffff"/> <textview Android: id = "@ + ID/download_file_size" Android: layout_width = "wrap_content" Android: layout_height = "wrap_content" Android: text = "0 kb" Android: textcolor = "# FF FFFF "/> </linearlayout> <imagebutton Android: Id =" @ + ID/stop_download "Android: layout_width =" wrap_content "Android: layout_height =" wrap_content "Android: authorization = "true" Android: layout_marginright = "120dp" Android: Background = "@ drawable/stop_download_btn" Android: visibility = "gone"/> </relativelayout> <progressbar Android: id = "@ + ID/download_file_progressbar" style = "? Android: ATTR/progressbarstylehorizontal "Android: layout_width =" 240dp "Android: layout_height =" wrap_content "Android: layout_gravity =" center "Android: padding =" 3dp "Android: progressdrawable = "@ drawable/download_progressbar"/> </linearlayout>

Add permission:

    <uses-permission android:name="android.permission.INTERNET" />    <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />    <uses-permission android:name="android.permission.WRITE_OWNER_DATA" />

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.