android版本更新问题

来源:互联网 发布:重庆宏宇软件 编辑:程序博客网 时间:2024/06/10 01:31


  做版本更新大多数情况会是在一个对话框里,在这里写的就是前些日子做的版本更新。

    首先需要判断一下手机的内存卡是否可用
public static boolean isAvailable() {return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState());}

    下面就是开始下载了:

public void startDownload(final String strPath) {Runnable r = new Runnable() {public void run() {try {doDownloadTheFile(strPath);openFile();//下载完成打开apk文件} catch (Exception e) {//Log.e(TAG, e.getMessage(), e);}}};new Thread(r).start();}

private FileOutputStream setOutPutStream(){FileOutputStream outStream = null;try {if(isAvailable()){outStream = new FileOutputStream(saveFileName,false);}else{//如果没有sd卡,那也不能不让人家下载更新啊,就下载到手机内存里吧。outStream=mContext.openFileOutput("FightLandlord.apk",Context.MODE_WORLD_READABLE|Context.MODE_WORLD_WRITEABLE);}} catch (Exception e) {// TODO: handle exception}return outStream;}
public void doDownloadTheFile(String strPath) throws Exception {if (!URLUtil.isNetworkUrl(strPath)) {Log.i("LogUtils", "下载地址错误!");} else {URL myURL = new URL(strPath);URLConnection conn = myURL.openConnection();conn.connect();InputStream is = conn.getInputStream();fileSize = conn.getContentLength();FileOutputStream outputStream = setOutPutStream();byte[] buffer = new byte[1024];downLoadSize = 0;int len;try {while ((len = is.read(buffer)) != -1) {outputStream.write(buffer, 0, len);downLoadSize += len;Message message1 = new Message();message1.what = 0;handler.sendMessage(message1);//此handler用于更新进度}} catch (OutOfMemoryError e) {Toast.makeText(mContext, "内存不足!", Toast.LENGTH_SHORT).show();outputStream.close();is.close();e.printStackTrace();}try {outputStream.close();is.close();} catch (Exception ex) {ex.printStackTrace();}}}
private void openFile() {Intent intent = new Intent();intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);intent.setAction(android.content.Intent.ACTION_VIEW);if(isAvailable()){intent.setDataAndType(Uri.parse("file://" + saveFileName.toString()), "application/vnd.android.package-archive");}else{intent.setDataAndType(Uri.fromFile(new File(mContext.getFilesDir().getAbsolutePath()+"/FightLandlord.apk")), "application/vnd.android.package-archive");}mContext.startActivity(intent);}
Handler handler = new Handler(){public void handleMessage(android.os.Message msg) {if (msg.what == 0) {progressBar.setProgress(downLoadSize * 100/fileSize);progressText.setText(downLoadSize*100/fileSize+"%");if(downLoadSize/fileSize >= 1){dismiss();//下载完成对话框消失}}};};

到此,主要部分已经贴出来了,需要主要的是OOM问题(这里应该不会出现什么问题,我已经测过多种机型了)。



0 0
原创粉丝点击