Automatic update of Android software (Network XML parsing and local xml Software Version)

Source: Internet
Author: User

Put XML into the network space --- version. xml. url address should be normal ***/***. apk
<Update>
<Version> 5 </version>
<Name> yuanbao </name>
 

<Url> http://cdn.market.hiapk.com/data/upload//2012/06_27/13/yuanbao.co.

Cc_13.02.apk
</Url>
</Update>
---------------- Main
Package gognzibai. co. cc;

Import android. app. Activity;
Import android. OS. Bundle;
Import android. view. View;
Import android. view. View. OnClickListener;
Import android. widget. Button;


Public class MainActivity extends Activity
{
@ Override
Public void onCreate (Bundle savedInstanceState)
{
Super. onCreate (savedInstanceState );
SetContentView (R. layout. main );
// Button update
Button updateBtn = (Button) findViewById

(R. id. btnUpdate );
UpdateBtn. setOnClickListener (new OnClickListener ()
{
@ Override
Public void onClick (View v)
{
UpdateManager manager = new

UpdateManager (MainActivity. this );

Manager. checkUpdate ();
}
});
 
}
}


----------------- ParseXmlService. java
Package gongzibai. co. cc;

Import java. io. InputStream;
Import java. util. HashMap;

Import javax. xml. parsers. DocumentBuilder;
Import javax. xml. parsers. DocumentBuilderFactory;

Import org. w3c. dom. Document;
Import org. w3c. dom. Element;
Import org. w3c. dom. Node;
Import org. w3c. dom. NodeList;

// Parse xml
Public class ParseXmlService {
Public HashMap <String, String> parseXml (
InputStream inStream)
Throws Exception {
HashMap <String, String> hashMap = new HashMap <String,

String> ();

 
DocumentBuilderFactory factory = DocumentBuilderFactory
. NewInstance ();
 
DocumentBuilder builder = factory
. NewDocumentBuilder ();
 
Document document = builder
. Parse (inStream );
 
Element root = document
. GetDocumentElement ();
 
NodeList childNodes = root
. GetChildNodes ();
For (int j = 0; j <childNodes
. GetLength (); j ++ ){

Node childNode = (Node) childNodes
. Item (j );
If (childNode. getNodeType () =

Node. ELEMENT_NODE ){
Element childElement = (Element)

ChildNode;

If ("version"
. Equals (childElement

. GetNodeName ())){
HashMap. put (
"Version ",
ChildElement

. GetFirstChild ()

. GetNodeValue ());
}

Else if ("name"
. Equals (childElement

. GetNodeName ()))){
HashMap. put (
"Name ",
ChildElement

. GetFirstChild ()

. GetNodeValue ());
}

Else if ("url"
. Equals (childElement

. GetNodeName ()))){
HashMap. put (
"Url ",
ChildElement

. GetFirstChild ()

. GetNodeValue ());
}
}
}
Return hashMap;
}
}

------------- Update management. UpdateManager. java

Package gongzibai. co. cc;

Import java. io. File;
Import java. io. FileOutputStream;
Import java. io. IOException;
Import java. io. InputStream;
Import java.net. HttpURLConnection;
Import java.net. MalformedURLException;
Import java.net. URL;
Import java. util. HashMap;

Import android. app. AlertDialog;
Import android. app. Dialog;
Import android. app. AlertDialog. Builder;
Import android. content. Context;
Import android. content. DialogInterface;
Import android. content. Intent;
Import android. content. DialogInterface. OnClickListener;
Import android. content. pm. PackageManager. NameNotFoundException;
Import android.net. Uri;
Import android. OS. Environment;
Import android. OS. Handler;
Import android. OS. Message;
Import android. view. LayoutInflater;
Import android. view. View;
Import android. widget. ProgressBar;
Import android. widget. Toast;

 

Public class UpdateManager {
 
Private static final int DOWNLOAD = 1;
 
Private static final int DOWNLOAD_FINISH = 2;
 
HashMap <String, String> mHashMap;
 
Private String mSavePath;
 
Private int progress;
 
Private boolean cancelUpdate = false;

Private Context mContext;
 
Private ProgressBar mProgress;
Private Dialog mDownloadDialog;

Private Handler mHandler = new Handler (){
Public void handleMessage (
Message msg ){
Switch (msg. what ){

Case DOWNLOAD:

MProgress
. SetProgress (progress );
Break;
Case DOWNLOAD_FINISH:
// Install APK
InstallApk ();
Break;
Default:
Break;
}
};
};

Public UpdateManager (Context context ){
This. mContext = context;
}

// Check for updates
Public void checkUpdate (){
If (isUpdate ()){

ShowNoticeDialog ();
} Else {
Toast. makeText (
MContext,
R. string. soft_update_no,
Toast. LENGTH_LONG)
. Show ();
}
}

 
Private boolean isUpdate (){
 
Int versionCode = getVersionCode (mContext );
 
// Update the local XML
// InputStream inStream = ParseXmlService. class
//
//. GetResourceAsStream ("version. xml ");
// InputStream inStream = ParseXmlService. class
//. GetClassLoader ()
//. GetResourceAsStream (
// "Version1.xml ");
 
// Update the software by parsing the network xml
URL url = null;
Try {
Url = new URL (

Http://gongzibai.h001.sjsdidc.cn/version.xml ");
} Catch (MalformedURLException e1 ){
// TODO Auto-generated catch block
E1.printStackTrace ();
}
HttpURLConnection conn = null;
Try {
Conn = (HttpURLConnection) url
. OpenConnection ();
} Catch (IOException e1 ){
// TODO Auto-generated catch block
E1.printStackTrace ();
}
Conn. setConnectTimeout (5000 );
InputStream is = null;
Try {
Is = conn. getInputStream ();
} Catch (IOException e1 ){
// TODO Auto-generated catch block
E1.printStackTrace ();
}

 
ParseXmlService service = new ParseXmlService ();
Try {
MHashMap = service
. ParseXml (is );
} Catch (Exception e ){
E. printStackTrace ();
}
If (null! = MHashMap ){
Int serviceCode = Integer
. ValueOf (mHashMap
. Get

("Version "));

If (serviceCode> versionCode ){
Return true;
}
}
Return false;
}

 
Private int getVersionCode (
Context context ){
Int versionCode = 0;
Try {

VersionCode = context
. GetPackageManager ()
. GetPackageInfo (

"Gongzibai. co. cc ",
0). versionCode;
} Catch (NameNotFoundException e ){
E. printStackTrace ();
}
Return versionCode;
}

 
Private void showNoticeDialog (){
 
AlertDialog. Builder builder = new Builder (
MContext );
Builder. setTitle (R. string. soft_update_title );
Builder. setMessage (R. string. soft_update_info );
 
Builder. setPositiveButton (
R. string. soft_update_updatebtn,
New OnClickListener (){
@ Override
Public void onClick (
DialogInterface

Dialog,
Int which ){
Dialog. dismiss ();

ShowDownloadDialog ();
}
});
 
Builder. setNegativeButton (
R. string. soft_update_later,
New OnClickListener (){
@ Override
Public void onClick (
DialogInterface

Dialog,
Int which ){
Dialog. dismiss ();
}
});
Dialog noticeDialog = builder
. Create ();
NoticeDialog. show ();
}

 
Private void showDownloadDialog (){
 
AlertDialog. Builder builder = new Builder (
MContext );
Builder. setTitle (R. string. soft_updating );
 
Final LayoutInflater inflater = LayoutInflater
. From (mContext );
View v = inflater
. Inflate (

R. layout. softupdate_progress,
Null );
MProgress = (ProgressBar) v
. FindViewById (R. id. update_progress );
Builder. setView (v );
 
Builder. setNegativeButton (
R. string. soft_update_cancel,
New OnClickListener (){
@ Override
Public void onClick (
DialogInterface

Dialog,
Int which ){
Dialog. dismiss ();

CancelUpdate = true;
}
});
MDownloadDialog = builder
. Create ();
MDownloadDialog. show ();
 
DownloadApk ();
}

Private void downloadApk (){
 
New downloadApkThread (). start ();
}

Private class downloadApkThread
Extends Thread {
@ Override
Public void run (){
Try {

If (Environment

. GetExternalStorageState ()
. Equals

(Environment. MEDIA_MOUNTED )){

String sdpath = Environment

. GetExternalStorageDirectory ()
+ "/";
MSavePath = sdpath
+ "Download ";
URL url = new URL (
MHashMap. get

("Url "));

HttpURLConnection conn =

(HttpURLConnection) url

. OpenConnection ();
Conn. connect ();

Int length = conn

. GetContentLength ();

InputStream is = conn

. GetInputStream ();

File file = new File (
MSavePath );

If (! File. exists ()){
File. mkdir ();
}
File apkFile = new File (
MSavePath,
MHashMap. get

("Name "));
FileOutputStream fos = new

FileOutputStream (
ApkFile );
Int count = 0;

Byte buf [] = new byte [1024];

Do {
Int numread = is
. Read

(Buf );
Count + = numread;

SS = (int)

(Float) count/length) * 100 );

MHandler. sendEmptyMessage (DOWNLOAD );
If (numread <= 0 ){

MHandler. sendEmptyMessage (DOWNLOAD_FINISH );
Break;
}

Fos. write (buf,
0,

Numread );
} While (! CancelUpdate );
Fos. close ();
Is. close ();
}
} Catch (MalformedURLException e ){
E. printStackTrace ();
} Catch (IOException e ){
E. printStackTrace ();
}

MDownloadDialog. dismiss ();
}
};

 
Private void installApk (){
File apkfile = new File (
MSavePath,
MHashMap. get ("name "));
If (! Apkfile. exists ()){
Return;
}
 
Intent I = new Intent (
Intent. ACTION_VIEW );
I. setDataAndType (
Uri. parse ("file ://"
+ Apkfile

. ToString ()),
"Application/vnd. android. package-

Archive ");
MContext. startActivity (I );
}
}

By gongzibai
 

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.