您的位置:首页 > 移动开发 > Android开发

android版本更新问题

2013-12-31 13:39 337 查看
  做版本更新大多数情况会是在一个对话框里,在这里写的就是前些日子做的版本更新。

    首先需要判断一下手机的内存卡是否可用:
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问题(这里应该不会出现什么问题,我已经测过多种机型了)。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐