Android Project Mobile Security Defender (02)

Source: Internet
Author: User
Tags response code

Directory
    • Project Structure diagram
    • Source
    • Run results
    • Project Source Code
Project Structure diagram

Source Code Listing 01. Splashactivity.java
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;import 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.animation.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_success = 10;private static final int Server_error = 11;private static final int server_url_error = 12;private static final int protocol_error = 13;private STA Tic Final int io_error = 14;private static final int xml_parse_error = 15;private static final int download_success = 16;p rivate static final int download_error = 17;protected static final String TAG = "splashactivity";p rivate long STARTTIME;PR Ivate relativelayout rl_splash;private long endtime;private progressdialog pd;private Handler Handler = new Handler () {Pub LIC 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 (), "Incorrect server path", Toast.length_ LONG). Show ();//Loadmainui (); Break;case SERVER_ERROR:Toast.makeText (Getapplicationcontext (), "Server internal exception", Toast.length_long). Show ();//Loadmainui (); break;case get_info_success:string serverversion = Info.getversion (); String CurrentVersion = GetVersion (), if (Currentversion.equals (serverversion)) {log.i (TAG, "version number same as enter main interface");// Loadmainui ();} else {log.i (TAG, "version number is not the same, Upgrade dialog box"); Showupdatedialog ();} Break;case download_success:log.i (TAG, "file download succeeded");//File File = (file) msg.obj;//installapk (file); Break;case Download_ ERROR:Toast.makeText (Getapplicationcontext (), "Download Data exception", Toast.length_long). Show ();//Loadmainui (); break;}};};/ * * Show upgrade prompt dialog box */protected void Showupdatedialog () {//Create dialog box constructor Alertdialog.builder Builder = new Builder (this);//Settings dialog box The Hint content Builder.seticon (getresourceS (). Getdrawable (r.drawable.notification));//Set Upgrade title Builder.settitle ("Upgrade Prompt");//Set Upgrade prompt content Builder.setmessage ( Info.getdescription ());//Create a download progress bar PD = new ProgressDialog (splashactivity.this);//Set the progress bar to display the prompt message pd.setmessage ("Downloading" );//Specifies that the download progress bar is displayed as a 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 (); @Overridepublic void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);// Set to no title bar requestwindowfeature (window.feature_no_title);//set 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 number:" + getversion ()); Alphaanimation AA = new Alphaanimation (0.3f, 1.0f); aa.setduration (+); rl_splash.startanimation (AA);//1. The connection server gets the configuration information on the server. New Thread (New Checkversiontask ()) {}.start ();} /** * Network Check the app's version number is the same as the version number on the server * * @author Administrator * */private class Checkversiontask implements Runnable {public V OID Run () {///Gets the CONFIG. sdcard file below, and if the file does not exist, the file will be created automatically sharedpreferences SP = getsharedpreferences ("config", Mode_ PRIVATE);//By the SP object to get the Boolean value of AutoUpdate, if the key does not exist, the default return Trueboolean autoupdate = Sp.getboolean ("AutoUpdate", true); /auto Update does not turn on if (!autoupdate) {try {//sleep 2 seconds is to play animation Thread.Sleep (),} catch (Interruptedexception e) {E.printstacktrace ();} Sleep 2 seconds play after the animation is completed into the main program interface//Loadmainui ();} StartTime = System.currenttimemillis (); Message msg = Message.obtain (); try {//Get the connection address of the configuration information for the service side string ServerURL = Getresources (). getString (R.string.serverurl); URL url = new URL (serverurl); HttpURLConnection conn = (httpurlconnection) Url.openconNection (); Conn.setrequestmethod ("GET");//Set Request mode Conn.setconnecttimeout (); int code = Conn.getresponsecode ();// Gets the response code if (code = = 200) {///Response code = 200, which indicates a successful connection with the server InputStream is = Conn.getinputstream (); info = Updateinfoparser.getupdateinfo (is); endTime = System.currenttimemillis (); Long resulttime = Endtime-starttime;if ( Resulttime <) {try {thread.sleep (2000-resulttime);} catch (Interruptedexception e) {e.printstacktrace ();}} Msg.what = Get_info_success;handler.sendmessage (msg);} else {//server state error. Msg.what = Server_error;handler.sendmessage (msg); endTime = System.currenttimemillis (); long Resulttime = Endtime-starttime;if (Resulttime <) {try {thread.sleep (2000-resulttime);} catch (Interruptedexcep tion 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 is in the corresponding manifest file in our apk (after extracting the APK directly, we can see the corresponding manifest file), * The version number is Android:versionname= "1.0" in the Manifest node * When an application is loaded into the phone, The APK is copied to the Data/app directory of the phone (that is, the system), * 6. So to get the version number, we need to get the system-related services, we can obtain the information in the APK * * </pre> * * @return */private String getversion () {//Get the System Package Manager. Has got the object-oriented wrapper of the apk packagemanager pm = This.getpackagemanager (); try {//parameter one: The current application's package name parameter two: Optional additional message, which we can't use here, can be defined as 0PackageInfo info = pm.getpackageinfo (getpackagename (), 0);//Returns the version number of the current application return info.versionname;} catch (Exception e) {//The exception that the package name does not find, theoretically, the exception cannot occur e.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 ioexception */public static UpdateInfo ge Tupdateinfo (InputStream is) throws Xmlpullparserexception, IOException {//Get an instance of Pull parsing xmlpullparser parser = Xml.newpullparser ();//The file to be parsed is streamed into Parser.setinput (IS, "UTF-8");//Create a Updateinfo instance that holds the data from the parsed XML, The object is eventually returned UpdateInfo info = new UpdateInfo ();//Gets the event type that is currently triggered int type = Parser.geteventtype ();//use while loop, if the resulting event code is the end of the document, Then end parsing while (type! = xmlpullparser.end_document) {if (type = = Xmlpullparser.start_tag) {//Start element if ("version". Equals ( Parser.getname ())) {//determine if the current element is the element that the reader needs to retrieve, the same as//because the content is also equivalent to a node, so the Nexttext () method that calls the parser object when fetching the content can get 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 version= "1.0" encoding= "Utf-8"?><resources>    <string name= "ServerURL" >http:// 192.168.0.101:8080/info.xml</string></resources>
Run results

Project Source Code

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

Android Project Mobile Security Defender (02)

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.