【手机安全卫士02】连接服务器获取更新信息

在上一篇文章中我们已经开发好了对应的启动页面,今天我们将继续开发进去启动页面时自动的连接服务器,获取服务器上的最新信息,如果服务器上的版本大于当前版本的话,则弹出对话框提示下载更新,否则直接进入主界面!下面是效果图:

 下面是SplashActivity的全部代码:

  1 package lq.wangzhen.mobilesafe;
  2 
  3 import java.io.IOException;
  4 import java.io.InputStream;
  5 import java.net.HttpURLConnection;
  6 import java.net.MalformedURLException;
  7 import java.net.URL;
  8 
  9 import lq.wangzhen.mobilesafe.domain.UpdateInfo;
 10 import lq.wangzhen.mobilesafe.engine.UpdateInfoParser;
 11 
 12 import org.xmlpull.v1.XmlPullParserException;
 13 
 14 import android.app.Activity;
 15 import android.app.AlertDialog;
 16 import android.app.AlertDialog.Builder;
 17 import android.content.DialogInterface;
 18 import android.content.DialogInterface.OnClickListener;
 19 import android.content.Intent;
 20 import android.content.pm.PackageInfo;
 21 import android.content.pm.PackageManager;
 22 import android.content.pm.PackageManager.NameNotFoundException;
 23 import android.os.Bundle;
 24 import android.os.Handler;
 25 import android.os.Message;
 26 import android.util.Log;
 27 import android.widget.TextView;
 28 import android.widget.Toast;
 29 
 30 public class SplashActivity extends Activity {
 31     private TextView tv_splash_version;
 32     private UpdateInfo info;
 33     
 34     private static final int GET_INFO_SUCCESS = 10;
 35     private static final int SERVER_ERROR = 11;
 36     private static final int SERVER_URL_ERROR = 12;
 37     private static final int IO_ERROR = 13;
 38     private static final int XML_PARSER_ERROR = 14;
 39     protected static final String TAG = "SplashActivity";
 40     
 41     private Handler handler = new Handler(){
 42 
 43         @Override
 44         public void handleMessage(Message msg) {
 45             switch (msg.what) {
 46             case XML_PARSER_ERROR:
 47                 Toast.makeText(getApplicationContext(), "XML解析异常", Toast.LENGTH_LONG).show();
 48                 loadMainUI();   //加载主界面
 49                 break;
 50             case IO_ERROR:
 51                 Toast.makeText(getApplicationContext(), "IO异常", Toast.LENGTH_LONG).show();
 52                 loadMainUI(); //加载主界面
 53                 break;
 54             case SERVER_URL_ERROR:
 55                 Toast.makeText(getApplicationContext(), "服务器URL出错", Toast.LENGTH_LONG).show();
 56                 loadMainUI(); //加载主界面
 57                 break;
 58             case SERVER_ERROR:
 59                 Toast.makeText(getApplicationContext(), "服务器异常", Toast.LENGTH_LONG).show();
 60                 loadMainUI();//加载主界面
 61                 break;
 62             case GET_INFO_SUCCESS:
 63                 String serverVersion = info.getVersion();   //取得服务器上的版本号
 64                 String currentVersion = getVersion();       //取得当前应用的版本号
 65                 if(currentVersion.equals(serverVersion)){   //判断两个版本号是否相同
 66                     Log.i(TAG, "版本号相同,进入主界面!");
 67                     loadMainUI();                //如果版本号相同,则进入主界面
 68                 }else{
 69                     Log.i(TAG, "版本号不相同,对话框!");
 70                     showUpdateDialog();                     //如果版本号不相同,则加载更新对话框
 71                 }
 72                 break;
 73 
 74             default:
 75                 break;
 76             }
 77         }
 78         
 79     };
 80     //加载主界面
 81     public void loadMainUI(){   
 82         Intent intent = new Intent(this,MainActivity.class);
 83         startActivity(intent);
 84         finish();   //结束当前的Activity
 85     }
 86     //显示升级对话框
 87     protected void showUpdateDialog() {
 88         AlertDialog.Builder builder = new Builder(this);    //实例化对话框
 89         builder.setIcon(getResources().getDrawable(R.drawable.notification));   //添加图标
 90         builder.setTitle("升级提示");   //添加标题
 91         builder.setMessage(info.getDescription());   //添加内容
 92         builder.setPositiveButton("升级", new OnClickListener() {    //点击升级时的操作方法
 93             @Override
 94             public void onClick(DialogInterface dialog, int which) {
 95                 Log.i(TAG, "升级,地址:"+info.getApkurl());
 96             }
 97         });
 98         builder.setNegativeButton("取消", new OnClickListener() {    //点击取消时的操作方法
 99             @Override
100             public void onClick(DialogInterface dialog, int which) {
101                 loadMainUI();
102             }
103         });
104         builder.create().show();   //显示对话框
105     }
106     @Override
107     protected void onCreate(Bundle savedInstanceState) {
108         super.onCreate(savedInstanceState);
109         setContentView(R.layout.activity_splash);
110         this.tv_splash_version = (TextView) this.findViewById(R.id.tv_splash_version);
111         this.tv_splash_version.setText("版本号:"+getVersion());   //设置应用程序的版本号
112         new Thread(new CheckVersionTask()){}.start();    //启动一个线程进行服务器连接判断版本号是否相同
113     }
114     
115     private class CheckVersionTask implements Runnable{
116         @Override
117         public void run() {
118             Message msg = Message.obtain();
119             //1、取得服务器地址
120             String serverUrl = getResources().getString(R.string.serverurl);   //取得服务器地址
121             //2、连接服务器
122             try {
123                 URL url = new URL(serverUrl);   
124                 HttpURLConnection conn = (HttpURLConnection) url.openConnection();
125                 conn.setConnectTimeout(5000);
126                 conn.setRequestMethod("GET");
127                 int code = conn.getResponseCode();
128                 if(code == 200){
129                     InputStream is = conn.getInputStream();    //取得服务器返回的内容
130                     info = UpdateInfoParser.getUpdateInfo(is);   //调用自己编写的方法,将输入流转换为UpdateInfo对象
131                     msg.what = GET_INFO_SUCCESS;
132                     handler.sendMessage(msg);
133                 }else{
134                     msg.what = SERVER_ERROR;
135                     handler.sendMessage(msg);
136                 }
137             } catch (MalformedURLException e) {
138                 msg.what = SERVER_URL_ERROR;
139                 handler.sendMessage(msg);
140                 handler.sendMessage(msg);
141             } catch (IOException e) {
142                 msg.what = IO_ERROR;
143                 handler.sendMessage(msg);
144                 e.printStackTrace();
145             } catch (XmlPullParserException e) {
146                 msg.what = XML_PARSER_ERROR;
147                 handler.sendMessage(msg);
148                 e.printStackTrace();
149             }
150         }
151     }
152     /**
153      * 取得应用的版本号
154      * @return
155      */
156     public String getVersion(){
157         PackageManager pm = getPackageManager();   //取得包管理器的对象,这样就可以拿到应用程序的管理对象
158         try {
159             PackageInfo info = pm.getPackageInfo(getPackageName(), 0);   //得到应用程序的包信息对象
160             return info.versionName;   //取得应用程序的版本号
161         } catch (NameNotFoundException e) {
162             e.printStackTrace();
163             //此异常不会发生
164             return "";
165         }
166     }
167 }

 

以上代码中用到的UpdateInfoParser.getUpdateInfo()方法,如下:

 1 package lq.wangzhen.mobilesafe.engine;
 2 
 3 import java.io.IOException;
 4 import java.io.InputStream;
 5 
 6 import org.xmlpull.v1.XmlPullParser;
 7 import org.xmlpull.v1.XmlPullParserException;
 8 
 9 import android.util.Xml;
10 
11 import lq.wangzhen.mobilesafe.domain.UpdateInfo;
12 
13 public class UpdateInfoParser {
14 
15     public static UpdateInfo getUpdateInfo(InputStream is) throws XmlPullParserException, IOException{
16         XmlPullParser parser = Xml.newPullParser();   //取得XmlPullParser解析器,准备对XML进行解析
17         parser.setInput(is, "UTF-8");
18         UpdateInfo info = new UpdateInfo();    //实例化UpdateInfo对象
19         int type = parser.getEventType();
20         while(type != XmlPullParser.END_DOCUMENT){
21             if(type==XmlPullParser.START_TAG){
22                 if("version".equals(parser.getName())){
23                     String version = parser.nextText();
24                     info.setVersion(version);
25                 }else if("description".equals(parser.getName())){
26                     String description = parser.nextText();
27                     info.setDescription(description);
28                 }else if("apkurl".equals(parser.getName())){
29                     String apkurl = parser.nextText();
30                     info.setApkurl(apkurl);
31                 }
32             }
33             type = parser.next();
34         }
35         return info;
36     }
37 }

 

以上代码中用到的UpdateInfo类,此类是根据服务器中提供的info.xml对象编写的:

 1 package lq.wangzhen.mobilesafe.domain;
 2 
 3 public class UpdateInfo {
 4 
 5     private String version;   //服务器上的版本号
 6     private String description;  //升级信息
 7     private String apkurl;    //apk下载地址
 8     public String getVersion() {
 9         return version;
10     }
11     public void setVersion(String version) {
12         this.version = version;
13     }
14     public String getDescription() {
15         return description;
16     }
17     public void setDescription(String description) {
18         this.description = description;
19     }
20     public String getApkurl() {
21         return apkurl;
22     }
23     public void setApkurl(String apkurl) {
24         this.apkurl = apkurl;
25     }
26     
27     
28 }

 

在layout文件夹中新建立main.xml布局文件,作为应用程序的主界面,如下:

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 3     android:layout_width="match_parent"
 4     android:layout_height="match_parent"
 5     android:orientation="vertical" >
 6     
 7     <TextView 
 8         android:id="@+id/test"
 9         android:layout_width="wrap_content"
10         android:layout_height="wrap_content"
11         android:text="mainUI"/>
12 
13 </LinearLayout>

 

建立对应的MainActivity.java,加载main.xml:

 1 package lq.wangzhen.mobilesafe;
 2 
 3 import android.app.Activity;
 4 import android.os.Bundle;
 5 
 6 public class MainActivity extends Activity {
 7 
 8     @Override
 9     protected void onCreate(Bundle savedInstanceState) {
10         super.onCreate(savedInstanceState);
11         setContentView(R.layout.main);
12     }
13 
14 }

 

在mainfest.xml文件中配置MainActivity:

1 <activity android:name="lq.wangzhen.mobilesafe.MainActivity"></activity> 

 

因为要访问网络,别忘了加入访问网络的权限哦:

1 <uses-permission android:name="android.permission.INTERNET"/>

 对应的源码下载地址:http://pan.baidu.com/share/link?shareid=1241370091&uk=1646729842

 

 

 

 

posted @ 2013-09-12 22:45  悟空65  阅读(1177)  评论(3编辑  收藏  举报