Android security guard (02) and android security guard

Source: Internet
Author: User

Android security guard (02) and android security guard
Directory

  • Project Structure
  • Source code
  • Running result
  • Project source code
Project Structure

Package com. coderdream. mobilesafe. activity; import java. io. IOException; import java. io. inputStream; import java.net. httpURLConnection; import java.net. malformedURLException; import java.net. protocolException; import java.net. URL; import org. xmlpull. v1.XmlPullParserException; import android. app. activity; import android. app. alertDialog; import android. app. alertDialog. builder; import android. app. progressDialog; I Mport android. content. dialogInterface; import android. content. dialogInterface. onClickListener; import android. content. sharedPreferences; import android. content. pm. packageInfo; import android. content. pm. packageManager; import android. OS. bundle; import android. OS. handler; import android. OS. message; import android. util. log; import android. view. window; import android. view. windowManager; import android. view. anima Tion. alphaAnimation; import android. widget. relativeLayout; import android. widget. textView; import android. widget. toast; import com. coderdream. mobilesafe. r; import com. coderdream. mobilesafe. domain. updateInfo; import com. coderdream. mobilesafe. engine. updateInfoParser; public class SplashActivity extends Activity {private TextView TV _splash_version; private UpdateInfo info; private static final int GET_INFO_SU CCESS = 10; private static final int SERVER_ERROR = 11; private static final int SERVER_URL_ERROR = 12; private static final int PROTOCOL_ERROR = 13; private static final int IO_ERROR = 14; private static final int XML_PARSE_ERROR = 15; private static final int DOWNLOAD_SUCCESS = 16; private static final int DOWNLOAD_ERROR = 17; protected static final String TAG = "SplashActivity"; private long startTime; p Rivate RelativeLayout rl_splash; private long endTime; private ProgressDialog pd; private Handler handler = new Handler () {public void handleMessage (android. OS. message msg) {switch (msg. what) {case XML_PARSE_ERROR: Toast. makeText (getApplicationContext (), "xml parsing error", Toast. LENGTH_LONG ). show (); // loadMainUI (); break; case IO_ERROR: Toast. makeText (getApplicationContext (), "I/O error", Toast. LENGTH_LONG ). show ();/ /LoadMainUI (); break; case PROTOCOL_ERROR: Toast. makeText (getApplicationContext (), "protocol not supported", Toast. LENGTH_LONG ). show (); // loadMainUI (); break; case SERVER_URL_ERROR: Toast. makeText (getApplicationContext (), "the server path is incorrect", Toast. LENGTH_LONG ). show (); // loadMainUI (); break; case SERVER_ERROR: Toast. makeText (getApplicationContext (), "Internal Server exception", Toast. LENGTH_LONG ). show (); // loadMainUI (); break; case GET_INFO_SUCCESS: S Tring serverversion = info. getVersion (); String currentversion = getVersion (); if (currentversion. equals (serverversion) {Log. I (TAG, "Enter the main interface with the same version number"); // loadMainUI ();} else {Log. I (TAG, "upgrade dialog box"); showUpdateDialog ();} break; case DOWNLOAD_SUCCESS: Log. I (TAG, "File downloaded successfully"); // file File = (File) msg. obj; // installApk (file); break; case DOWNLOAD_ERROR: Toast. makeText (getApplicationContext (), "data download exception", Toast. LEN GTH_LONG ). show (); // loadMainUI (); break ;};};/*** display the upgrade prompt dialog box */protected void showUpdateDialog () {// create the constructor AlertDialog of the dialog box. builder builder = new Builder (this); // set the prompt content builder in the dialog box. setIcon (getResources (). getDrawable (R. drawable. notification); // set the upgrade title builder. setTitle ("upgrade prompt"); // set the upgrade prompt content builder. setMessage (info. getDescription (); // create a download progress bar pd = new ProgressDialog (SplashActivity. this); // set the prompt message when the progress bar is displayed. Pd. setMessage ("downloading"); // specifies that the download progress bar is in the horizontal shape pd. setProgressStyle (ProgressDialog. STYLE_HORIZONTAL); // set the Upgrade button builder. setPositiveButton ("Upgrade", new OnClickListener () {public void onClick (DialogInterface dialog, int which) {// loadMainUI () ;}}); builder. setNegativeButton ("cancel", new OnClickListener () {public void onClick (DialogInterface dialog, int which) {// loadMainUI () ;}}); builder. create (). show () ;}@ Overridepub Lic void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); // set to requestWindowFeature (Window. FEATURE_NO_TITLE); // set it to full screen mode getWindow (). setFlags (WindowManager. layoutParams. FLAG_FULLSCREEN, WindowManager. layoutParams. FLAG_FULLSCREEN); setContentView (R. layout. activity_splash); rl_splash = (RelativeLayout) findViewById (R. id. rl_splash); TV _splash_version = (TextView) findViewById (R. Id. TV _splash_version); TV _splash_version.setText ("version:" + getVersion (); AlphaAnimation aa = new AlphaAnimation (0.3f, 1.0f); aa. setDuration (2000); rl_splash.startAnimation (aa); // 1. connect to the server to obtain the configuration information on the server. new Thread (new CheckVersionTask ()){}. start ();}/*** check whether the application version is the same as the version number on the server. ** @ author Administrator **/private class CheckVersionTask implements Runnable {public void run () {// obtain the config. xml files, such If the file does not exist, the file SharedPreferences sp = getSharedPreferences ("config", MODE_PRIVATE) will be automatically created; // The boolean value corresponding to autoupdate will be obtained by the sp object, if this key does not exist, trueboolean autoupdate = sp is returned by default. getBoolean ("autoupdate", true); // if (! Autoupdate) {try {// sleeping for 2 seconds is to play the animation Thread. sleep (2000);} catch (InterruptedException e) {e. printStackTrace ();} // After the animation is played for 2 seconds, enter the main interface of the program // loadMainUI ();} startTime = System. currentTimeMillis (); Message msg = Message. obtain (); try {// connection address for obtaining server configuration information String serverurl = getResources (). getString (R. string. serverurl); URL url = new URL (serverurl); HttpURLConnection conn = (HttpURLConnection) url. openConnection (); co Nn. setRequestMethod ("GET"); // sets the Request Method conn. setConnectTimeout (5000); int code = conn. getResponseCode (); // get the response code if (code = 200) {// when the response code is 200, it indicates that the connection to the server is successful InputStream is = conn. getInputStream (); info = UpdateInfoParser. getUpdateInfo (is); endTime = System. currentTimeMillis (); long resulttime = endTime-startTime; if (resulttime <2000) {try {Thread. sleep (2000-resulttime);} catch (InterruptedException e) {e. PrintStackTrace () ;}} msg. what = GET_INFO_SUCCESS; handler. sendMessage (msg);} else {// server status error. msg. what = SERVER_ERROR; handler. sendMessage (msg); endTime = System. currentTimeMillis (); long resulttime = endTime-startTime; if (resulttime <2000) {try {Thread. sleep (2000-resulttime);} catch (InterruptedException e) {e. printStackTrace () ;}}} catch (MalformedURLException e) {e. printStackTrace (); msg. what = SERVER_URL_ERROR; handler. sendMessage (msg);} catch (ProtocolException e) {msg. what = PROTOCOL_ERROR; handler. sendMessage (msg); e. printStackTrace ();} catch (IOException e) {msg. what = IO_ERROR; handler. sendMessage (msg); e. printStackTrace ();} catch (XmlPullParserException e) {msg. what = XML_PARSE_ERROR; handler. sendMessage (msg); e. printStackTrace () ;}}/ *** <pre> * gets the version number of the current application. * The version number exists in the corresponding configuration file in our APK (after you extract the APK directly, you can see the corresponding configuration file). * The version number is android in the manifest node: versionName = "1.0" * When an application is installed on a mobile phone, the apk is copied to the data/app directory of the mobile phone (that is, in the system), * 6. So if you want to get the version number, you need to get the system-related service to get the information in the apk ** </pre> ** @ return */private String getVersion () {// obtain the system Package Manager. You have obtained the object-oriented PackageManager pm = this For apk. getPackageManager (); try {// parameter 1: package name of the current application parameter 2: optional additional message. We cannot use it here. It can be defined as 0 PackageInfo info = pm. getPackageInfo (getPackageName (), 0); // return the current application version number return info. versionName;} catch (Exception e) {// an Exception not found in the package name. Theoretically, this Exception cannot occur. printStackTrace (); return "";}}}Listing 02. UpdateInfo. java

package com.coderdream.mobilesafe.domain;public class UpdateInfo {private String version;private String description;private String apkurl;public String getVersion() {return version;}public void setVersion(String version) {this.version = version;}public String getDescription() {return description;}public void setDescription(String description) {this.description = description;}public String getApkurl() {return apkurl;}public void setApkurl(String apkurl) {this.apkurl = apkurl;}}

Listing 03. UpdateInfoParser. java

Package com. coderdream. mobilesafe. engine; import java. io. IOException; import java. io. inputStream; import org. xmlpull. v1.XmlPullParser; import org. xmlpull. v1.XmlPullParserException; import android. util. xml; import com. coderdream. mobilesafe. domain. updateInfo; /***** Parse XML data **/public class UpdateInfoParser {/***** @ param is * input stream of the xml file * @ return updateinfo object * @ throws XmlPullParserException * @ throws IOEx Ception */public static UpdateInfo getUpdateInfo (InputStream is) throws XmlPullParserException, IOException {// get a Pull-parsed instance XmlPullParser parser = Xml. newPullParser (); // the file to be parsed is passed into parser. setInput (is, "UTF-8"); // create an UpdateInfo instance to store the data in the parsed xml, and finally return the object UpdateInfo info = new UpdateInfo (); // obtain the currently triggered event type int type = parser. getEventType (); // use the while loop. If the obtained Event code is the end of the document, parse the while (type! = XmlPullParser. END_DOCUMENT) {if (type = XmlPullParser. START_TAG) {// start element if ("version ". equals (parser. getName () {// determine whether the current element is the element that the reader needs to retrieve. The same below // because the content is also equivalent to a node, call the nextText () of the parser object to obtain the content () method to obtain the content String version = parser. nextText (); info. setVersion (version);} else if ("description ". equals (parser. getName () {String description = parser. nextText (); info. setDescription (description);} else if ("apkurl ". equals (parser. getName () {String apkurl = parser. nextText (); info. setApkurl (apkurl);} type = parser. next () ;}return info ;}}
Listing 03. config. xml
<?xml version="1.0" encoding="utf-8"?><resources>    <string name="serverurl">http://192.168.0.101:8080/info.xml</string></resources>
Running result

Engineering source code

Address: http://download.csdn.net/detail/xuxiheng/8147099

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.