`

有无SD卡情况下,下载Apk,并安装

 
阅读更多
有无SD卡情况下,下载Apk,并安装



今天遇到一个问题,我的任务是 下载一个apk,并安装,但是在无SD卡的情况下,包解析错误


我的思路是:
有SD卡 就下载到SD卡,无SD卡就下载到getCacheDir()下面

但是 因为这个目录是只能自己app使用,所以安装的时候 就报了包解析错误的问题

我猜测原因是因为没有权限访问/data/data/com.xxx.xx/cache这个目录,所以 需要设置个权限。

解决方法


File tFile = null;
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) { 
  tFile = new File(FILE_PATH);
}else{
  tFile = new File(mContext.getFilesDir(), URL_APP.hashCode()+".apk");
}


然后 下载完成的时候,一般都有一个rename的过程,这个时候 需要做一下处理

private void renameFile(){
		File file=new File(targetFile+DOWNLOAD_SUFFIX);
		File target=new File(targetFile);
		if(target.exists())
			target.delete();
		if(isInnerDir(file)){
			FileOutputStream tFos = null;
			FileInputStream tFis = null;
			try {
				tFos = FexApplication.getInstance().openFileOutput(target.getName(), Context.MODE_WORLD_READABLE);
				tFis = FexApplication.getInstance().openFileInput(file.getName());
				byte[] buffer = new byte[1024];
				int length = 0;
				while((length = tFis.read(buffer)) !=-1){
					tFos.write(buffer, 0, length);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}finally {
				try {
					if(tFos!=null){
						tFos.close();
					}
					if(tFis!=null){
						tFis.close();
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}else{
			try {
				file.renameTo(target);
			} catch (Exception e) {
				e.printStackTrace();
			}		
		}
	}
	
	private boolean isInnerDir(File tFile){
		return tFile.getAbsolutePath().contains("data/data") && !tFile.getAbsolutePath().contains("Android");
	}



主要就是 这个方法
openFileOutput(target.getName(), Context.MODE_WORLD_READABLE);



逻辑比较简单,直接看代码就行




分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics