Android Application check update summary

Source: Internet
Author: User

Android Application check update summary

Each application should have an interface between the main interface to display the company or team information, introduce the software, and check for updates. Remind the user to update the latest version in time for more and better user experience. This article will summarize the implementation, and do not look for your own projects in the future.

Traditionally, we define the class implementing this function as splashActivity.

On this page, you should initialize some data, such as copying files to the system directory, copying the packaged database to the system directory, and checking whether the software version is updated.

1. copying a file to the system directory has been written as a tool class, so you only need to obtain the source address and target address of the file to complete the copy. The following code retrieves the SD card file directory on the android platform is as follows:


/*** Get the file path and status information ** @ return */private List
 
  
GetFiles () {File path = null; List
  
   
Infos = new ArrayList
   
    
(); MyFileInfo info = null; // determines whether the SD card is available if (Environment. getExternalStorageState (). equals (Environment. MEDIA_MOUNTED) {path = Environment. getExternalStorageDirectory (); File [] files = path. listFiles (); for (File file: files) {// set the path as if (file. getPath ()! = Null) {info = new MyFileInfo (); info. setPath (file. getPath (); infos. add (info); info = null ;}} else {Toast. makeText (FileSearchActivity. this, "SD card unavailable! ", 300). show ();} return infos ;}
   
  
 
File copying method:

/*** @ Warning The name of file must be end. xls * @ param res The resource file * @ param des The destination * @ return * @ throws FileNotFoundException */public static boolean toCopy (String res, String des) {boolean flag = false; // input the source File file = new File (res); FileInputStream fr = null; // copy the target File desFile = new file (des); FileOutputStream bw = null; try {fr = new FileInputStream (file); bw = new FileOut PutStream (desFile); // bufferbyte [] B = new byte [512]; while (fr. read (B )! =-1) {bw. write (B);} bw. flush (); flag = true;} catch (FileNotFoundException e) {// TODO Auto-generated catch blocke. printStackTrace ();} catch (IOException e) {// TODO Auto-generated catch blocke. printStackTrace ();} finally {if (fr! = Null) try {fr. close ();} catch (IOException e) {// TODO Auto-generated catch blocke. printStackTrace ();} if (bw! = Null) {try {bw. close ();} catch (IOException e) {// TODO Auto-generated catch blocke. printStackTrace () ;}} return flag ;}

How to get the android app system directory:

File file = new File (getFilesDir (), "xxx.xls"); that is, under the data/package name/files directory in android.
You can copy the SD card files to the application system directory by using the preceding method.
 
2. Copy the database to the system directory

(1) obtain the system file directory:

Final File file = new File (getFilesDir (), "xxx. db ");

(2) obtain the input stream of files located in the asset directory

InputStream is = getAssets (). open ("xxx. db ");

GetResources ()

* Read File resources: 1. read the file resources under res/raw, and use the following method to obtain the input stream for write operations · InputStream is = getResources (). openRawResource (R. id. filename); 2. read the file resources under assets and obtain the input stream for write operations. · AssetManager am = null; · am = getAssets (); · InputStream is = am. open ("filename ");

 

 

2. Read the database copied to the system and obtain the database reference. Then you can operate the database.

SQLiteDatabase db = SQLiteDatabase. openDatabase (path, null,

SQLiteDatabase. OPEN_READONLY );

 

Note: The path to the database file copied to the system is public static final String path = "/data/application package name/files/database file ";

The database you created is in the databases folder.

 

Tool class:
Public class CopyFileToSystem {public CopyFileToSystem () {// TODO Auto-generated constructor stub}/*** copy the file to the system folder * @ param in * @ param destPath */public static void copyFile (InputStream in, string destPath) {// target File file File = new file (destPath); FileOutputStream fos = null; try {fos = new FileOutputStream (File); int len = 0; byte [] buffer = new byte [1024]; while (len = in. read (buffer ))! =-1) {fos. write (buffer, 0, len);} fos. flush (); fos. close (); in. close () ;}catch (Exception e ){}}}


3. Check for updates
(1) obtain the application version number first.
/*** Get application version information * @ return application version */private String getAppVersion () {PackageManager pm = getPackageManager (); PackageInfo info = null; try {info = pm. getPackageInfo (getPackageName (), 0); if (info! = Null) {return info. versionName;} catch (NameNotFoundException e) {e. printStackTrace ();} return "";}

(2) connect to the configuration file of the network resolution server to obtain the latest application version number, as shown below:
1) the xml file on the server is as follows:
   
   
    
     
2.0
    
    
     
Download the new version to experience more new features !!!
    Http: // 192.168.253.1: 8080/TouristManager.apk
   
2) connect to the server to obtain the xml file for parsing the input stream
Public class UpdateInfoParser {/*** resolve the update information returned by the server * @ param is the stream returned by the server * @ return if an exception occurs, null is returned; */public static UpdateInfo getUpdateInfo (InputStream is) {try {XmlPullParser parser = Xml. newPullParser (); parser. setInput (is, "UTF-8"); int type = parser. getEventType (); UpdateInfo info = null; while (type! = XmlPullParser. END_DOCUMENT) {switch (type) {case XmlPullParser. START_TAG: if ("info ". equals (parser. getName () {info = new UpdateInfo ();} else if ("version ". equals (parser. getName () {info. setVersion (parser. nextText ();} else if ("description ". equals (parser. getName () {info. setDescription (parser. nextText ();} else if ("apkurl ". equals (parser. getName () {info. setApkurl (parser. nextText ();} break;} type = parser. next ();} return info;} catch (Exception e) {e. printStackTrace (); return null ;}}}

The source code of the entire splash is as follows:
Package com. example. ehrmanager; import java. io. file; import java. io. IOException; import java. io. inputStream; import java.net. httpURLConnection; import java.net. malformedURLException; import java.net. URL; import android. app. activity; import android. app. alertDialog; import android. app. alertDialog. builder; import android. app. progressDialog; import android. content. dialogInterface; import android. content. dialogInte Rface. onClickListener; import android. content. intent; import android. content. sharedPreferences; import android. content. pm. packageInfo; import android. content. pm. packageManager; import android. content. pm. packageManager. nameNotFoundException; import android. content. res. resources. notFoundException; import android.net. uri; import android. OS. bundle; import android. OS. environment; import android. OS. handler; import Android. OS. message; import android. util. log; import android. view. menu; import android. view. animation. alphaAnimation; import android. widget. textView; import android. widget. toast; import com. example. ehrmanager. domain. updateInfo; import com. example. ehrmanager. utils. downLoadUtil; import com. example. ehrmanager. utils. updateInfoParser; public class SplashActivity extends Activity {private TextView mTVversion; // display Shows the application version private String mVersion; // The application version public static final int PARSE_XML_ERROR = 10; public static final int PARSE_XML_SUCCESS = 11; public static final int SERVER_ERROR = 12; public static final int URL_ERROR = 13; public static final int NETWORK_ERROR = 14; private static final int DOWNLOAD_SUCCESS = 15; private static final int DOWNLOAD_ERROR = 16; protected static final String TAG = "SplashActivity"; pr Ivate static final int COPYDATA_ERROR = 17; private UpdateInfo updateInfo; private ProgressDialog pd; // download progress dialog box private Handler handler = new Handler () {public void handleMessage (android. OS. message msg) {switch (msg. what) {case PARSE_XML_ERROR: Toast. makeText (getApplicationContext (), "xml parsing failed", 0 ). show (); // enter the main program interface loadMainUI (); break; case SERVER_ERROR: Toast. makeText (getApplicationContext (), "server exception", 0 ). Show (); // enter the main program interface loadMainUI (); break; case URL_ERROR: Toast. makeText (getApplicationContext (), "server address exception", 0 ). show (); // enter the main program interface loadMainUI (); break; case NETWORK_ERROR: Toast. makeText (getApplicationContext (), "network exception", 0 ). show (); // enter the main interface loadMainUI (); break; case PARSE_XML_SUCCESS: if (getAppVersion (). equals (updateInfo. getVersion () {// enter the main interface Log of the program. I (TAG, "same version number, enter the main interface"); loadMainUI ();} else {Log. I (TAG, "the version number is not consistent The upgrade prompt dialog box "); showUpdateDialog ();} break; case DOWNLOAD_ERROR: Toast. makeText (getApplicationContext (), "Download failed", 0 ). show (); // enter the main program interface loadMainUI (); break; case DOWNLOAD_SUCCESS: File file = (File) msg. obj; Log. I (TAG, "Install apk" + file. getAbsolutePath (); // install apkinstallApk (file); finish (); break; case COPYDATA_ERROR: Toast. makeText (getApplicationContext (), "failed to load database", 0 ). show (); break ;};};@ Overrideprotected void on Create (Bundle savedInstanceState) {super. onCreate (savedInstanceState); intiViews ();}/*** initialization component */private void intiViews () {setContentView (R. layout. activity_splash); mTVversion = (TextView) this. findViewById (R. id. app_version); mVersion = getAppVersion (); // obtain the application version mTVversion. setText (mVersion); // connect to the server to check for version updates. new Thread (new CheckVersionTask ()). start (); AlphaAnimation aa = new AlphaAnimation (0.2f, 1.0f); aa. set Duration( 2000); findViewById (R. id. rl_splash ). startAnimation (aa);}/*** get application version information * @ return application version */private String getAppVersion () {PackageManager pm = getPackageManager (); packageInfo info = null; try {info = pm. getPackageInfo (getPackageName (), 0); if (info! = Null) {return info. versionName ;}} catch (NameNotFoundException e) {e. printStackTrace ();} return "";}/*** enter the main interface */private void loadMainUI () {Intent intent = new Intent (SplashActivity. this, HomeActivity. class); startActivity (intent); this. finish () ;}@ Overridepublic boolean onCreateOptionsMenu (Menu menu) {// Inflate the menu; this adds items to the action bar if it is present. getMenuInflater (). inflate (R. men U. splash, menu); return true;}/*** prompt dialog box for automatic upgrade */protected void showUpdateDialog () {AlertDialog. builder builder = new Builder (this); builder. setTitle ("upgrade reminder"); builder. setMessage (updateInfo. getDescription (); builder. setPositiveButton ("OK", new OnClickListener () {@ Overridepublic void onClick (DialogInterface dialog, int which) {String apkurl = updateInfo. getApkurl (); pd = new ProgressDialog (SplashActivit Y. this); pd. setTitle ("upgrade operation"); pd. setMessage ("downloading... "); pd. setProgressStyle (ProgressDialog. STYLE_HORIZONTAL); pd. show (); Log. I (TAG, "Install after download:" + apkurl); final File file = new File (Environment. getExternalStorageDirectory (), DownLoadUtil. getFileName (apkurl); // determines whether the SD card is available, only available. if (Environment. getExternalStorageState (). equals (Environment. MEDIA_MOUNTED) {new Thread () {public void run () {File savedFile = Do WnLoadUtil. download (updateInfo. getApkurl (), file. getAbsolutePath (), pd); Message msg = Message. obtain (); if (savedFile! = Null) {// download successful msg. what = DOWNLOAD_SUCCESS; msg. obj = savedFile;} else {// download failed msg. what = DOWNLOAD_ERROR;} handler. sendMessage (msg); pd. dismiss ();};}. start ();} else {Toast. makeText (getApplicationContext (), "SD card unavailable", 0 ). show (); loadMainUI () ;}}); builder. setNegativeButton ("cancel", new OnClickListener () {@ Overridepublic void onClick (DialogInterface dialog, int which) {loadMainUI () ;}}); builder. create (). show (); // Builder. show ();} private class CheckVersionTask implements Runnable {@ Overridepublic void run () {SharedPreferences sp = getSharedPreferences ("config", MODE_PRIVATE); boolean isupdate = sp. getBoolean ("update", true); if (! Isupdate) {try {Thread. sleep (1000);} catch (InterruptedException e) {e. printStackTrace ();} loadMainUI (); return;} long startTime = System. currentTimeMillis (); Message msg = Message. obtain (); try {URL url = new URL (getResources (). getString (R. string. serverurl); HttpURLConnection conn = (HttpURLConnection) url. openConnection (); conn. setRequestMethod ("GET"); conn. setConnectTimeout (1500); int code = conn. getResponseCode (); if (code = 200) {InputStream is = conn. getInputStream (); updateInfo = UpdateInfoParser. getUpdateInfo (is); if (updateInfo = null) {// TODO: xml parsing failed msg. what = PARSE_XML_ERROR;} else {// parsing successful msg. what = PARSE_XML_SUCCESS;} else {// TODO: internal server error. msg. what = SERVER_ERROR ;}} catch (MalformedURLException e) {msg. what = URL_ERROR; // http://e.printStackTrace ();} catch (NotFoundException e) {msg. what = URL_ERROR; // e. printStackTrace ();} catch (IOException e) {msg. what = NETWORK_ERROR; e. printStackTrace ();} finally {long endTime = System. currentTimeMillis (); long dTime = endTime-startTime; if (dTime <2000) {try {Thread. sleep (2000-dTime);} catch (InterruptedException e) {e. printStackTrace () ;}} handler. sendMessage (msg) ;}}/ *** install an apk file ** @ param File */protected void installApk (file File) {Intent intent = new Intent (); intent. setAction ("android. intent. action. VIEW "); intent. addCategory ("android. intent. category. DEFAULT "); intent. setDataAndType (Uri. fromFile (file), "application/vnd. android. package-archive "); startActivity (intent );}}
Tool source code:
Download new APK
Package com. example. ehrmanager. utils; import java. io. file; import java. io. fileOutputStream; import java. io. inputStream; import java.net. httpURLConnection; import java.net. URL; import android. app. progressDialog; public class DownLoadUtil {/*** file download operation *** @ param serverPath * Server File Path * @ param savedPath * Local save path * @ param pd progress bar dialog box * @ return download return successful object download failure return null */public static File download (String serve RPath, String savedPath, ProgressDialog pd) {try {URL url = new URL (serverPath); HttpURLConnection conn = (HttpURLConnection) url. openConnection (); conn. setConnectTimeout (5000); conn. setRequestMethod ("GET"); int code = conn. getResponseCode (); if (code = 200) {pd. setMax (conn. getContentLength (); InputStream is = conn. getInputStream (); File file = new File (savedPath); FileOutputStream fos = new FileOutputS Tream (file); byte [] buffer = new byte [1024]; int len = 0; int total = 0; while (len = is. read (buffer ))! =-1) {fos. write (buffer, 0, len); total + = len; pd. setProgress (total); Thread. sleep (20);} fos. flush (); fos. close (); is. close (); return file;} else {return null ;}} catch (Exception e) {e. printStackTrace (); return null ;}/ *** get the name of the Server File * @ param serverPath * @ return */public static String getFileName (String serverPath) {return serverPath. substring (serverPath. lastIndexOf ("/") + 1 );}}







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.