Android应用程序更新并下载

时间:2024-04-15 07:23:45

创建一个新类,名为UpdateManager,代码如下:

  1 import java.io.BufferedReader;
  2 import java.io.File;
  3 import java.io.FileOutputStream;
  4 import java.io.IOException;
  5 import java.io.InputStream;
  6 import java.io.InputStreamReader;
  7 import java.net.HttpURLConnection;
  8 import java.net.MalformedURLException;
  9 import java.net.URL;
 10 import com.af.mobile.R;
 11 import android.app.AlertDialog;
 12 import android.app.Dialog;
 13 import android.app.AlertDialog.Builder;
 14 import android.content.Context;
 15 import android.content.DialogInterface;
 16 import android.content.Intent;
 17 import android.content.DialogInterface.OnClickListener;
 18 import android.content.pm.PackageManager.NameNotFoundException;
 19 import android.net.Uri;
 20 import android.os.Environment;
 21 import android.os.Handler;
 22 import android.os.Message;
 23 import android.view.LayoutInflater;
 24 import android.view.View;
 25 import android.widget.ProgressBar;
 26 import android.widget.Toast;
 27 
 28 
 29 public class UpdateManager
 30 {private URL url=null;
 31     /* 下载中 */
 32     private static final int DOWNLOAD = 1;
 33     /* 下载结束 */
 34     private static final int DOWNLOAD_FINISH = 2;
 35     /* 保存解析的XML信息 */
 36     //HashMap<String, String> mHashMap;
 37     /* 下载保存路径 */
 38     private String mSavePath;
 39     /* 记录进度条数量 */
 40     private int progress;
 41     /* 是否取消更新 */
 42     private boolean cancelUpdate = false;
 43 
 44     private Context mContext;
 45     /* 更新进度条 */
 46     private ProgressBar mProgress;
 47     private Dialog mDownloadDialog;
 48 
 49     private Handler mHandler = new Handler()
 50     {
 51         public void handleMessage(Message msg)
 52         {
 53             switch (msg.what)
 54             {
 55             // 正在下载
 56             case DOWNLOAD:
 57                 // 设置进度条位置
 58                 mProgress.setProgress(progress);
 59                 break;
 60             case DOWNLOAD_FINISH:
 61                 // 安装文件
 62                 installApk();
 63                 break;
 64             default:
 65                 break;
 66             }
 67         };
 68     };
 69 
 70     public UpdateManager(Context context)
 71     {
 72         this.mContext = context;
 73     }
 74 
 75     public void checkUpdate()
 76     {
 77         if (isUpdate())
 78         {
 79             showNoticeDialog();
 80         } else
 81         {
 82             
 83         }
 84     }
 85 
 86     /**
 87      * 检查软件是否有更新版本
 88      * 
 89      * @return
 90      */
 91     private boolean isUpdate()
 92     {
 93         // 获取当前软件版本
 94         Double versionCode = getVersionCode(mContext);
 95     
 96             Double serviceCode = 1.2;
 97             // 版本判断
 98             if (serviceCode > versionCode)
 99             {
100                 return true;
101             }
102         
103         return false;
104     }
105 
106     // 获取软件版本号
107     
108     private Double getVersionCode(Context context)
109     {
110         Double versionCode = 0.0;
111         try
112         {
113             // 获取软件版本号,对应AndroidManifest.xml下android:versionCode
114             versionCode = (double) context.getPackageManager().getPackageInfo("com.af.mobile", 0).versionCode;
115         } catch (NameNotFoundException e)
116         {
117             e.printStackTrace();
118         }
119         return versionCode;
120     }
121 
122     
123      //显示软件更新对话框
124     
125     private void showNoticeDialog()
126     {
127         AlertDialog.Builder builder = new Builder(mContext);
128         builder.setTitle("软件更新");
129         String string=download("http://192.168.0.102:9313/daojuserver/uploads/version.xml");//xml的下载地址
130         builder.setMessage(string);
131 
132         builder.setPositiveButton("更新", new OnClickListener()
133         {
134             @Override
135             public void onClick(DialogInterface dialog, int which)
136             {
137                 dialog.dismiss();
138                 // 显示下载对话框
139                 showDownloadDialog();
140             }
141         });
142         // 稍后更新
143         builder.setNegativeButton("稍后更新", new OnClickListener()
144         {
145             @Override
146             public void onClick(DialogInterface dialog, int which)
147             {
148                 dialog.dismiss();
149             }
150         });
151         Dialog noticeDialog = builder.create();
152         noticeDialog.show();
153     }
154 
155     // 显示软件下载对话框
156      
157     private void showDownloadDialog()
158     {
159         // 构造软件下载对话框
160         AlertDialog.Builder builder = new Builder(mContext);
161         builder.setTitle("djfkjd");//提示信息内容
162         // 给下载对话框增加进度条
163         final LayoutInflater inflater = LayoutInflater.from(mContext);
164         View v = inflater.inflate(R.layout.softupdate_progress, null);
165         mProgress = (ProgressBar) v.findViewById(R.id.update_progress);
166         builder.setView(v);
167         // 取消更新
168         builder.setNegativeButton("取消更新", new OnClickListener()
169         {
170             @Override
171             public void onClick(DialogInterface dialog, int which)
172             {
173                 dialog.dismiss();
174                 // 设置取消状态
175                 cancelUpdate = true;
176             }
177         });
178         mDownloadDialog = builder.create();
179         mDownloadDialog.show();
180         // 现在文件
181         downloadApk();
182     }
183 
184 
185     private void downloadApk()
186     {
187         // 启动新线程下载软件
188         new downloadApkThread().start();
189     }
190 
191     private class downloadApkThread extends Thread
192     {
193         @Override
194         public void run()
195         {
196             try
197             {
198                 // 判断SD卡是否存在,并且是否具有读写权限
199                 if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
200                 {
201                     // 获得存储卡的路径
202                     String sdpath = Environment.getExternalStorageDirectory() + "/";
203                     mSavePath = sdpath + "download";
204                     URL url = new URL("http://192.168.0.102:9313/daojuserver/uploads/SpMobile.apk");//apk下载地址地址
205                     // 创建连接
206                     HttpURLConnection conn = (HttpURLConnection) url.openConnection();
207                     conn.connect();
208                     // 获取文件大小
209                     int length = conn.getContentLength();
210                     // 创建输入流
211                     InputStream is = conn.getInputStream();
212 
213                     File file = new File(mSavePath);
214                     if (!file.exists())
215                     {
216                         file.mkdir();
217                     }
218                     File apkFile = new File(mSavePath, "dhfudh");
219                     FileOutputStream fos = new FileOutputStream(apkFile);
220                     int count = 0;
221                     // 缓存
222                     byte buf[] = new byte[1024];
223                     // 写入到文件中
224                     do
225                     {
226                         int numread = is.read(buf);
227                         count += numread;
228                         // 计算进度条位置
229                         progress = (int) (((float) count / length) * 100);
230                         // 更新进度
231                         mHandler.sendEmptyMessage(DOWNLOAD);
232                         if (numread <= 0)
233                         {
234                             mHandler.sendEmptyMessage(DOWNLOAD_FINISH);
235                             break;
236                         }
237                         fos.write(buf, 0, numread);
238                     } while (!cancelUpdate);
239                     fos.close();
240                     is.close();
241                 }
242             } catch (MalformedURLException e)
243             {
244                 e.printStackTrace();
245             } catch (IOException e)
246             {
247                 e.printStackTrace();
248             }
249             // 取消下载对话框显示
250             mDownloadDialog.dismiss();
251         }
252     };
253     
254     private void installApk()
255     {
256         File apkfile = new File(mSavePath, "dhfudh");
257         if (!apkfile.exists())
258         {
259             return;
260         }
261         // 通过Intent安装APK文件
262         Intent i = new Intent(Intent.ACTION_VIEW);
263         i.setDataAndType(Uri.parse("file://" + apkfile.toString()), "application/vnd.android.package-archive");
264         mContext.startActivity(i);
265     }
266     public String download(String urlString)
267     {
268         StringBuffer sbBuffer=new StringBuffer();
269         String  line=null;
270         BufferedReader buffer=null;
271     try {
272         url=new URL(urlString);
273         HttpURLConnection urlConn=(HttpURLConnection) url.openConnection();
274         buffer=new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
275         while((line=buffer.readLine())!=null)
276         {
277             sbBuffer.append(line);
278         }
279     } catch (Exception e) {
280         // TODO: handle exception
281         e.printStackTrace();
282     }
283     finally
284     {
285         try {
286             buffer.close();
287         } catch (Exception e2) {
288             // TODO: handle exception
289             e2.printStackTrace();
290         }
291     }
292     return sbBuffer.toString();
293     }
294 }
UpdateManager

在Android应用程序Main界面

1 if(isOpenNetwork())//判断是否有网络
2         {
3            UpdateManager manager = new    UpdateManager(Main.this);
4         // 检查软件更新
5         manager.checkUpdate();
6             
7         }
判断

判断移动端是否有网络

isOpenNetwork
 1 private boolean isOpenNetwork() {
 2         ConnectivityManager connManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
 3         NetworkInfo networkInfo = connManager.getActiveNetworkInfo();
 4 
 5         if (networkInfo != null) {
 6             // 2.获取当前网络连接的类型信息
 7             int networkType = networkInfo.getType();
 8             if (ConnectivityManager.TYPE_WIFI == networkType) {
 9                 // 当前为wifi网络
10             } else if (ConnectivityManager.TYPE_MOBILE == networkType) {
11                 // 当前为mobile网络
12             }
13             return connManager.getActiveNetworkInfo().isAvailable();
14         }
15 
16         return false;
17     }