App Update (Android) and app update android

Source: Internet
Author: User

App Update (Android) and app update android

App Update (Android)

 

Preface: Currently, General Android software is constantly updated. when you open an app, if there is a new version, it will prompt you to have a new version to be updated. This function is implemented in this project. In addition, there are two ways to force update and update prompt. When there is an update, a prompt box will pop up. Click Download to create a progress bar for download in the notification, and click Cancel, cancel the update.

 

Effect:

 

Development Environment: AndroidStudio2.1.2 + gradle-2.10

 

Some code:

Public class UpdateVersionController {private Context context; // update the instance private AppUpdateInfo info of the file; // The current version number private int versionCode; // prompt the user to update the dialog private Dialog dialog; // download progress bar private ProgressDialog pd; public static UpdateVersionController getInstance (Context context) {return new UpdateVersionController (context);} public UpdateVersionController (Context context) {this. context = context ;} Public void normalCheckUpdateInfo () {// get the version number: the version number here is in the build of the project. in gradle, you can see the copied parameter/** defaconfig config {applicationId "com. zhh. test "minSdkVersion 16 targetSdkVersion 23 versionCode 1 versionName" 1.0 "} */versionCode = getVerCode (context); // 19 checkVersionTask ();} public void forceCheckUpdateInfo () {// force update generally does not require versionCode = getVerCode (context); // 19 info = new AppUpdateInfo (); info. setUrl (" Http: // 60.210.21.89/clusters? Sign = baidu @ baidu & wshc_tag = 0 & wsts_tag = 58c7bde2 & wsid_tag = 7c5a47c8 & wsiphost = ipdbm "); info. setVercode (2); // It depends on info for every update. setVername ("2.0"); // version name info. setApkname ("com.hellotext.1309171635.apk"); info. setAppname ("Hello"); info. setForceUpp ("yes"); info. setUppcontent ("1. hello, I have updated \ n2. The interface is very nice. \ n3. UI effect optimization "); // updateApp ();}/*** Step 1: Get version information */private void checkVersionTask () {// obtain the information of the new version of the app through network loading // no value is requested here. info = new AppUpdateInfo (); info. setUrl ("http: // 60.210.21.89/clusters" +
"Com.hellotext.1309171635.apk? Sign = baidu @ baidu & wshc_tag = 0 & wsts_tag = 58c7bde2 & wsid_tag = 7c5a47c8 & wsiphost = ipdbm "); info. setVercode (2); // It depends on info for every update. setVername ("2.0"); // version name info. setApkname ("com.hellotext.1309171635.apk"); info. setAppname ("Hello"); info. setForceUpp ("no"); info. setUppcontent ("1. hello, I have updated \ n2. The interface is very nice. \ n3. UI effect optimization "); // updateApp ();} private void updateApp () {if (null! = Info & info. getVercode ()> versionCode) {// 20> 19. You can update showUpdataDialog () ;}else {Toast. makeText (context, "it is already the latest version ~ ", Toast. LENGTH_SHORT ). show () ;}} private Button cancelBtn;/*** Step 2: a dialog box is displayed prompting you to update */protected void showUpdataDialog () {Dialog = new dialog (context, android. r. style. theme_Dialog); dialog. getWindow (). setBackgroundDrawableResource (android. r. color. transparent); dialog. setContentView (R. layout. activity_updater); dialog. setCanceledOnTouchOutside (false); dialog. setCancelable (false); (TextView) dialog. f IndViewById (R. id. content )). setText (info. getUppcontent (); cancelBtn = (Button) dialog. findViewById (R. id. cancel); cancelBtn. setVisibility ("yes ". equals (info. getForceUpp ())? View. GONE: View. VISIBLE); // cancel cancelBtn update. setOnClickListener (new View. onClickListener () {@ Override public void onClick (View v) {dialog. dismiss () ;}}); // confirm to update the dialog. findViewById (R. id. OK ). setOnClickListener (new View. onClickListener () {@ Override public void onClick (View v) {dialog. dismiss (); downLoadApk () ;}}); dialog. findViewById (R. id. market ). setOnClickListener (new View. onClickListener () {@ Override public void onClick (View v) {Intent intent = new Intent (Intent. ACTION_VIEW); intent. setData (Uri. parse ("market: // details? Id = Hello "); context. startActivity (intent) ;}}); dialog. show ();}/*** Step 3: download the file */private void downLoadApk () {// progress bar dialog box pd = new ProgressDialog (context); pd. setProgressStyle (ProgressDialog. STYLE_HORIZONTAL); pd. setMessage ("downloading... "); pd. setCanceledOnTouchOutside (false); pd. setCancelable (false); // listens to the Return key -- prevents the download from clicking "Return pd. setOnKeyListener (new OnKeyListener () {@ Override public boolean onKey (DialogI Nterface dialog, int keyCode, KeyEvent) {if (keyCode = KeyEvent. KEYCODE_BACK & event. getRepeatCount () = 0) {Toast. makeText (context, "downloading... please wait", Toast. LENGTH_SHORT ). show (); return true;} else {return false ;}}); // if (! Environment. getExternalStorageState (). equals (Environment. MEDIA_MOUNTED) {Toast. makeText (context, "SD card unavailable ~ ", Toast. LENGTH_SHORT ). show ();} else {pd. show (); // The downloaded sub-Thread new Thread () {@ Override public void run () {try {// download the APK File file File = getFileFromServer (info. getUrl (), pd); sleep (1000); // install the APK file installApk (file); pd. dismiss (); // The progress bar closing dialog box} catch (Exception e) {Toast. makeText (context, "File Download failed ~ ", Toast. LENGTH_SHORT ). show (); pd. dismiss (); e. printStackTrace ();}}}. start () ;}}/*** download apk from server */public File getFileFromServer (String path, ProgressDialog pd) throws Exception {// if they are equal, the current sdcard is mounted on the mobile phone and is available if (Environment. getExternalStorageState (). equals (Environment. MEDIA_MOUNTED) {URL url = new URL (path); HttpURLConnection conn = (HttpURLConnection) url. openConnection (); conn. setCon NectTimeout (5000); // get the file size pd. setMax (conn. getContentLength ()/1024); InputStream is = conn. getInputStream (); File file = new File (Environment. getExternalStorageDirectory (). getPath () + "/blibao/merchant", "I _blibao_shop.apk"); // determine whether a folder is created if (! File. getParentFile (). exists () {file. getParentFile (). mkdirs ();} FileOutputStream fos = new FileOutputStream (file); BufferedInputStream bis = new BufferedInputStream (is); byte [] buffer = new byte [1024]; int len; int total = 0; while (len = bis. read (buffer ))! =-1) {fos. write (buffer, 0, len); total + = len; // obtain the current download volume pd. setProgress (total/1024);} fos. close (); bis. close (); is. close (); return file;} else {return null;}/*** install apk */protected void installApk (File file) {Intent intent = new Intent (); // execute the intent action. setAction (Intent. ACTION_VIEW); // the Data Type of the execution intent. setDataAndType (Uri. fromFile (file), "application/vnd. android. package-archive "); intent. addFlags (Intent. FLAG_ACTIVITY_NEW_TASK); context. startActivity (intent);}/*** get version name */public static String getVerName (Context context) {String verName = ""; try {// obtain packagemanager's instance PackageManager packageManager = context. getPackageManager (); // getPackageName () is the package name of your current class. 0 indicates obtaining the PackageInfo packInfo = packageManager. getPackageInfo (context. getPackageName (), 0); verName = packInfo. versionName;} catch (Exception e) {e. printStackTrace ();} return verName;}/*** get version number */public static int getVerCode (Context context) {int verCode =-1; try {// obtain packagemanager's instance PackageManager packageManager = context. getPackageManager (); // getPackageName () is the package name of your current class. 0 indicates obtaining the PackageInfo packInfo = packageManager. getPackageInfo (context. getPackageName (), 0); verCode = packInfo. versionCode;} catch (Exception e) {e. printStackTrace () ;}return verCode ;}}

 

Download source code...

 

 

 

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.