Android automatically updates apps

Source: Internet
Author: User

Android automatically updates apps

Currently, General android software is constantly updated. when you open an app, if there is a new version, it will prompt you that a new version needs to be updated. The applet implements this function.

A prompt box will pop up when there is an update. Click OK to create a progress bar in the notification for download. Click Cancel to cancel the update.

The following code details:

1. Create the layout file icationication_item.xml to generate a progress bar and a download icon in the notification bar.

 

 
  
   
         
     
    
   
  
 

2. Create an AppContext class that inherits from the Application.

 

 

Package com. test. application; import android. app. application; import android. content. context; import com. test. update. config. config; public class AppContext extends Application {private static AppContext appInstance; private Context context; public static AppContext getInstance () {return appInstance ;}@ Overridepublic void onCreate () {// TODO Auto-generated method stubsuper. onCreate (); appInstance = this; context = this. getBaseContext (); // get the current version number // try {// PackageInfo packageInfo = getApplicationContext ()//. getPackageManager (). getPackageInfo (getPackageName (), 0); // Config. localVersion = packageInfo. versionCode; // Config. serverVersion = 1; // assume that the server version is 2 and the local version is 1 by default. //} catch (NameNotFoundException e) {// e. printStackTrace (); //} initGlobal ();} public void initGlobal () {try {Config. localVersion = getPackageManager (). getPackageInfo (getPackageName (), 0 ). versionCode; // set the local version number Config. serverVersion = 2; // assume that the server version is 2 and the local version is 1 by default. In actual development, the latest version is obtained from the server, for more information about the interaction between android and the backend, see my other blog.} catch (Exception ex) {ex. printStackTrace ();}}}

3. Create a configuration file class Config. java, which defines some version-related constants.

 

 

Package com. test. update. config; public class Config {// version information public static int localVersion = 0; public static int serverVersion = 0; /* download package installation path */public static final String savePath =/sdcard/test/; public static final String saveFileName = savePath + test.apk ;}


 

4. Compile UpdateServcie. java

 

Package com. test. update; import java. io. file; import java. io. fileOutputStream; import java. io. inputStream; import java.net. httpURLConnection; import java.net. URL; import android. annotation. suppressLint; import android. app. notification; import android. app. icationicationmanager; import android. app. pendingIntent; import android. app. service; import android. content. intent; import android.net. uri; import android. OS. env Ironment; import android. OS. handler; import android. OS. IBinder; import android. OS. message; import android. widget. remoteViews; import com. test. update. config. config; public class UpdateService extends Service {// Title private int titleId = 0; // File storage private File updateDir = null; private File updateFile = null; // Download Status private final static int DOWNLOAD_COMPLETE = 0; private final static int DOWNLOAD_FAIL = 1; // pass Private icationicationmanager updateNotificationManager = null; private Notification updateNotification = null; // The Notification bar jumps to Intentprivate Intent updateIntent = null; private PendingIntent updatePendingIntent = null; /***** create a notification bar */RemoteViews contentView; // there are a lot of such download code, so I will not explain too much int downloadCount = 0; int currentSize = 0; long totalSize = 0; int updateTotalSize = 0; // prepare the download task in the onStartCommand () method: @ SuppressWarn Ings (deprecation) @ Overridepublic int onStartCommand (Intent intent, int flags, int startId) {// get the passed value titleId = intent. getIntExtra (titleId, 0); // create a file if (android. OS. environment. MEDIA_MOUNTED.equals (android. OS. environment. getExternalStorageState () {updateDir = new File (Environment. getExternalStorageDirectory (), Config. saveFileName); updateFile = new File (updateDir. getPath (), getResources (). getString (t ItleId) +. apk);} this. updateNotificationManager = (icationicationmanager) getSystemService (NOTIFICATION_SERVICE); this. updateNotification = new Notification (); // you can click the Notification bar to return to the main interface updateIntent = new Intent (this, UpdateActivity. class); updatePendingIntent = PendingIntent. getActivity (this, 0, updateIntent, 0); // sets the content updateNotification in the notification bar. icon = R. drawable. ic_launcher; updateNotification. tickerText = start Download; updateNotification. setLatestEventInfo (this, QQ, 0%, updatePendingIntent); // send a notification to updateNotificationManager. Y (0, updateNotification); // enable a new thread for downloading. If you use the Service for Synchronous downloading, this will cause ANR problems, the Service itself also blocks new Thread (new updateRunnable ()). start (); // This is the focus of the download, and is the return super. onStartCommand (intent, flags, startId) ;}@ Overridepublic IBinder onBind (Intent arg0) {// TODO Auto-generated method stubreturn null;} @ Suppr EssLint (HandlerLeak) private Handler updateHandler = new Handler () {@ Overridepublic void handleMessage (Message msg) {switch (msg. what) {case DOWNLOAD_COMPLETE: // click to install PendingIntentUri = uri. fromFile (updateFile); Intent installIntent = new Intent (Intent. ACTION_VIEW); installIntent. setDataAndType (uri, application/vnd. android. package-archive); updatePendingIntent = PendingIntent. getActivity (UpdateServi Ce. this, 0, installIntent, 0); updateNotification. defaults = Notification. DEFAULT_SOUND; // ringtone Notification updateNotification. setLatestEventInfo (UpdateService. this, QQ, download complete, click Install ., UpdatePendingIntent); updateNotificationManager. Y (0, updateNotification); // stop the service stopService (updateIntent); case DOWNLOAD_FAIL: // download failed updateNotification. setLatestEventInfo (UpdateService. this, QQ, download complete, click to install ., UpdatePendingIntent); updateNotificationManager. Y (0, updateNotification); default: stopService (updateIntent) ;}}; public long downloadUpdateFile (String downloadUrl, File saveFile) throws Exception {HttpURLConnection httpConnection = null; inputStream is = null; FileOutputStream fos = null; try {URL url = new URL (downloadUrl); httpConnection = (HttpURLConnection) url. openConnection (); httpConnection. set RequestProperty (User-Agent, PacificHttpClient); if (currentSize> 0) {httpConnection. setRequestProperty (RANGE, bytes = + currentSize +-);} httpConnection. setConnectTimeout (10000); httpConnection. setReadTimeout (20000); updateTotalSize = httpConnection. getContentLength (); if (httpConnection. getResponseCode () = 404) {throw new Exception (fail !);} Is = httpConnection. getInputStream (); fos = new FileOutputStream (saveFile, false); byte buffer [] = new byte [4096]; int readsize = 0; while (readsize = is. read (buffer)> 0) {fos. write (buffer, 0, readsize); totalSize + = readsize; // to Prevent the application from being tightened due to frequent notifications, if (downloadCount = 0) is notified only once when the percentage increases by 10) | (int) (totalSize * 100/updateTotalSize)-10> downloadCount) {downloadCount + = 10; updateNotification. setlatesteven Ti Nfo (UpdateService. this, is being downloaded, (int) totalSize * 100/updateTotalSize + %, updatePendingIntent);/***** here we use a custom view to display Notification */updateNotification. contentView = new RemoteViews (getPackageName (), R. layout. notification_item); updateNotification. contentView. setTextViewText (R. id. notificationTitle, being downloaded); updateNotification. contentView. setProgressBar (R. id. icationicationss, 100, downloadCount, fal Se); updateNotificationManager. Y (0, updateNotification) ;}} finally {if (httpConnection! = Null) {httpConnection. disconnect ();} if (is! = Null) {is. close () ;}if (fos! = Null) {fos. close () ;}} return totalSize;} class updateRunnable implements Runnable {Message message = updateHandler. obtainMessage (); public void run () {message. what = DOWNLOAD_COMPLETE; try {// Add Permissions
 
  
; If (! UpdateDir. exists () {updateDir. mkdirs ();} if (! UpdateFile. exists () {updateFile. createNewFile () ;}// download the function, using QQ as an example // Add Permissions
  
   
; Long downloadSize = downloadUpdateFile (http://softfile.3g.qq.com: 8080/msoft/179/1105/10753/mobileqq1.0(android1__build0198.apk, updateFile); if (downloadSize> 0) {// download successful updateHandler. sendMessage (message) ;}} catch (Exception ex) {ex. printStackTrace (); message. what = DOWNLOAD_FAIL; // download failed updateHandler. sendMessage (message );}}}}
  
 

5. Write the activity class UpdateActivity

 

 

Package com. test. update; import com. test. update. config. config; import android. support. v4.app. fragment; import android. app. activity; import android. app. alertDialog; import android. content. dialogInterface; import android. content. intent; import android. OS. bundle; import android. util. log; import android. view. layoutInflater; public class UpdateActivity extends Activity {@ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); checkVersion ();}/*** check the updated version */public void checkVersion () {if (Config. localVersion <Config. serverVersion) {Log. I (hgncxzy, ============================ ); // when a new version is found, the user is prompted to update AlertDialog. builder alert = new AlertDialog. builder (this); alert. setTitle (software upgrade ). setMessage (the new version is found. We recommend that you update it immediately .). setPositiveButton (Update, new DialogInterface. onClickListener () {public void onClick (DialogInterface Diener, int which) {// enable the update Service UpdateService // to better modularize update, you can upload updateService dependent values // such as layout ID, resource ID, and dynamically obtained title. Here we use app_name as an example: Intent updateIntent = new Intent (UpdateActivity. this, UpdateService. class); updateIntent. putExtra (titleId, R. string. app_name); startService (updateIntent );}}). setNegativeButton (cancel, new DialogInterface. onClickListener () {public void onClick (DialogInterface diich, int which) {dialog. dismiss () ;}}); alert. create (). show ();} else {// cleanup, skipped // cheanUpdateFile ()}}}

6. add permissions and load the service statically (load in the configuration file ).

 

 

 

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.