Android软件自动更新(自定义处理,不使用第三方)

来源:http://www.android100.org/html/201406/08/21956.html

XML放入网络空间---version.xml .url地址应该为正常***/*****.apk
<update>
 <version>5</version>
 <name>yuanbao</name>
 

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

cc_134532.apk
 </url>
</update>

 1 package gognzibai.co.cc;
 2 import android.app.Activity;
 3 import android.os.Bundle;
 4 import android.view.View;
 5 import android.view.View.OnClickListener;
 6 import android.widget.Button;
 7 
 8 public class MainActivity extends Activity
 9 {
10  @Override
11  public void onCreate(Bundle savedInstanceState)
12  {
13   super.onCreate(savedInstanceState);
14   setContentView(R.layout.main);
15   //按钮更新
16   Button updateBtn = (Button) findViewById
17 (R.id.btnUpdate);
18   updateBtn.setOnClickListener(new OnClickListener()
19   {
20    @Override
21    public void onClick(View v)
22    {
23     UpdateManager manager = new
24 UpdateManager(MainActivity.this);
25    
26     manager.checkUpdate();
27    }
28   });
29  
30  }
31 }
MainActivity
 1 package gongzibai.co.cc;
 2 import java.io.InputStream;
 3 import java.util.HashMap;
 4 import javax.xml.parsers.DocumentBuilder;
 5 import javax.xml.parsers.DocumentBuilderFactory;
 6 import org.w3c.dom.Document;
 7 import org.w3c.dom.Element;
 8 import org.w3c.dom.Node;
 9 import org.w3c.dom.NodeList;
10 //解析xml
11 public class ParseXmlService {
12  public HashMap<String, String> parseXml(
13    InputStream inStream)
14    throws Exception {
15   HashMap<String, String> hashMap = new HashMap<String,
16 String>();
17  
18   DocumentBuilderFactory factory = DocumentBuilderFactory
19     .newInstance();
20  
21   DocumentBuilder builder = factory
22     .newDocumentBuilder();
23  
24   Document document = builder
25     .parse(inStream);
26  
27   Element root = document
28     .getDocumentElement();
29  
30   NodeList childNodes = root
31     .getChildNodes();
32   for (int j = 0; j < childNodes
33     .getLength(); j++) {
34   
35    Node childNode = (Node) childNodes
36      .item(j);
37    if (childNode.getNodeType() ==
38 Node.ELEMENT_NODE) {
39     Element childElement = (Element)
40 childNode;
41    
42     if ("version"
43       .equals(childElement
44        
45 .getNodeName())) {
46      hashMap.put(
47        "version",
48        childElement
49         
50 .getFirstChild()
51         
52 .getNodeValue());
53     }
54    
55     else if (("name"
56       .equals(childElement
57        
58 .getNodeName()))) {
59      hashMap.put(
60        "name",
61        childElement
62         
63 .getFirstChild()
64         
65 .getNodeValue());
66     }
67    
68     else if (("url"
69       .equals(childElement
70        
71 .getNodeName()))) {
72      hashMap.put(
73        "url",
74        childElement
75         
76 .getFirstChild()
77         
78 .getNodeValue());
79     }
80    }
81   }
82   return hashMap;
83  }
84 }
ParseXmlService.java
  1 package gongzibai.co.cc;
  2 import java.io.File;
  3 import java.io.FileOutputStream;
  4 import java.io.IOException;
  5 import java.io.InputStream;
  6 import java.net.HttpURLConnection;
  7 import java.net.MalformedURLException;
  8 import java.net.URL;
  9 import java.util.HashMap;
 10 import android.app.AlertDialog;
 11 import android.app.Dialog;
 12 import android.app.AlertDialog.Builder;
 13 import android.content.Context;
 14 import android.content.DialogInterface;
 15 import android.content.Intent;
 16 import android.content.DialogInterface.OnClickListener;
 17 import android.content.pm.PackageManager.NameNotFoundException;
 18 import android.net.Uri;
 19 import android.os.Environment;
 20 import android.os.Handler;
 21 import android.os.Message;
 22 import android.view.LayoutInflater;
 23 import android.view.View;
 24 import android.widget.ProgressBar;
 25 import android.widget.Toast;
 26  
 27 public class UpdateManager {
 28  
 29  private static final int DOWNLOAD = 1;
 30  
 31  private static final int DOWNLOAD_FINISH = 2;
 32  
 33  HashMap<String, String> mHashMap;
 34  
 35  private String mSavePath;
 36  
 37  private int progress;
 38  
 39  private boolean cancelUpdate = false;
 40  private Context mContext;
 41  
 42  private ProgressBar mProgress;
 43  private Dialog mDownloadDialog;
 44  private Handler mHandler = new Handler() {
 45   public void handleMessage(
 46     Message msg) {
 47    switch (msg.what) {
 48   
 49    case DOWNLOAD:
 50    
 51     mProgress
 52       .setProgress(progress);
 53     break;
 54    case DOWNLOAD_FINISH:
 55     //安装APK
 56     installApk();
 57     break;
 58    default:
 59     break;
 60    }
 61   };
 62  };
 63  public UpdateManager(Context context) {
 64   this.mContext = context;
 65  }
 66  //检查更新
 67  public void checkUpdate() {
 68   if (isUpdate()) {
 69   
 70    showNoticeDialog();
 71   } else {
 72    Toast.makeText(
 73      mContext,
 74      R.string.soft_update_no,
 75      Toast.LENGTH_LONG)
 76      .show();
 77   }
 78  }
 79  
 80  private boolean isUpdate() {
 81  
 82   int versionCode = getVersionCode(mContext);
 83  
 84   //本地的XML更新
 85   // InputStream inStream = ParseXmlService.class
 86   //
 87   // .getResourceAsStream("version.xml");
 88   // InputStream inStream = ParseXmlService.class
 89   // .getClassLoader()
 90   // .getResourceAsStream(
 91   // "version1.xml");
 92  
 93   //解析网络xml进行更新软件
 94   URL url = null;
 95   try {
 96    url = new URL(
 97     
 98 "http://gongzibai.h001.sjsdidc.cn/version.xml");
 99   } catch (MalformedURLException e1) {
100    // TODO Auto-generated catch block
101    e1.printStackTrace();
102   }
103   HttpURLConnection conn = null;
104   try {
105    conn = (HttpURLConnection) url
106      .openConnection();
107   } catch (IOException e1) {
108    // TODO Auto-generated catch block
109    e1.printStackTrace();
110   }
111   conn.setConnectTimeout(5000);
112   InputStream is = null;
113   try {
114    is = conn.getInputStream();
115   } catch (IOException e1) {
116    // TODO Auto-generated catch block
117    e1.printStackTrace();
118   }
119  
120   ParseXmlService service = new ParseXmlService();
121   try {
122    mHashMap = service
123      .parseXml(is);
124   } catch (Exception e) {
125    e.printStackTrace();
126   }
127   if (null != mHashMap) {
128    int serviceCode = Integer
129      .valueOf(mHashMap
130        .get
131 ("version"));
132   
133    if (serviceCode > versionCode) {
134     return true;
135    }
136   }
137   return false;
138  }
139  
140  private int getVersionCode(
141    Context context) {
142   int versionCode = 0;
143   try {
144   
145    versionCode = context
146      .getPackageManager()
147      .getPackageInfo(
148       
149 "gongzibai.co.cc",
150        0).versionCode;
151   } catch (NameNotFoundException e) {
152    e.printStackTrace();
153   }
154   return versionCode;
155  }
156  
157  private void showNoticeDialog() {
158  
159   AlertDialog.Builder builder = new Builder(
160     mContext);
161   builder.setTitle(R.string.soft_update_title);
162   builder.setMessage(R.string.soft_update_info);
163  
164   builder.setPositiveButton(
165     R.string.soft_update_updatebtn,
166     new OnClickListener() {
167      @Override
168      public void onClick(
169        DialogInterface
170 dialog,
171        int which) {
172       dialog.dismiss();
173      
174       showDownloadDialog();
175      }
176     });
177  
178   builder.setNegativeButton(
179     R.string.soft_update_later,
180     new OnClickListener() {
181      @Override
182      public void onClick(
183        DialogInterface
184 dialog,
185        int which) {
186       dialog.dismiss();
187      }
188     });
189   Dialog noticeDialog = builder
190     .create();
191   noticeDialog.show();
192  }
193  
194  private void showDownloadDialog() {
195  
196   AlertDialog.Builder builder = new Builder(
197     mContext);
198   builder.setTitle(R.string.soft_updating);
199  
200   final LayoutInflater inflater = LayoutInflater
201     .from(mContext);
202   View v = inflater
203     .inflate(
204      
205 R.layout.softupdate_progress,
206       null);
207   mProgress = (ProgressBar) v
208     .findViewById(R.id.update_progress);
209   builder.setView(v);
210  
211   builder.setNegativeButton(
212     R.string.soft_update_cancel,
213     new OnClickListener() {
214      @Override
215      public void onClick(
216        DialogInterface
217 dialog,
218        int which) {
219       dialog.dismiss();
220      
221       cancelUpdate = true;
222      }
223     });
224   mDownloadDialog = builder
225     .create();
226   mDownloadDialog.show();
227  
228   downloadApk();
229  }
230  private void downloadApk() {
231  
232   new downloadApkThread().start();
233  }
234  private class downloadApkThread
235    extends Thread {
236   @Override
237   public void run() {
238    try {
239    
240     if (Environment
241      
242 .getExternalStorageState()
243       .equals
244 (Environment.MEDIA_MOUNTED)) {
245     
246      String sdpath = Environment
247       
248 .getExternalStorageDirectory()
249        + "/";
250      mSavePath = sdpath
251        + "download";
252      URL url = new URL(
253        mHashMap.get
254 ("url"));
255     
256      HttpURLConnection conn =
257 (HttpURLConnection) url
258       
259 .openConnection();
260      conn.connect();
261     
262      int length = conn
263       
264 .getContentLength();
265     
266      InputStream is = conn
267       
268 .getInputStream();
269      File file = new File(
270        mSavePath);
271     
272      if (!file.exists()) {
273       file.mkdir();
274      }
275      File apkFile = new File(
276        mSavePath,
277        mHashMap.get
278 ("name"));
279      FileOutputStream fos = new
280 FileOutputStream(
281        apkFile);
282      int count = 0;
283    
284      byte buf[] = new byte[1024];
285     
286      do {
287       int numread = is
288         .read
289 (buf);
290       count += numread;
291      
292       progress = (int)
293 (((float) count / length) * 100);
294     
295      
296 mHandler.sendEmptyMessage(DOWNLOAD);
297       if (numread <= 0) {
298       
299       
300 mHandler.sendEmptyMessage(DOWNLOAD_FINISH);
301        break;
302       }
303      
304       fos.write(buf,
305         0,
306        
307 numread);
308      } while (!cancelUpdate);
309      fos.close();
310      is.close();
311     }
312    } catch (MalformedURLException e) {
313     e.printStackTrace();
314    } catch (IOException e) {
315     e.printStackTrace();
316    }
317   
318    mDownloadDialog.dismiss();
319   }
320  };
321  
322  private void installApk() {
323   File apkfile = new File(
324     mSavePath,
325     mHashMap.get("name"));
326   if (!apkfile.exists()) {
327    return;
328   }
329  
330   Intent i = new Intent(
331     Intent.ACTION_VIEW);
332   i.setDataAndType(
333     Uri.parse("file://"
334       + apkfile
335        
336 .toString()),
337     "application/vnd.android.package-
338 archive");
339   mContext.startActivity(i);
340  }
341 }
UpdateManager.java
原文地址:https://www.cnblogs.com/Miami/p/4214571.html