解决下载后的apk解析错误问题

android段进行apk更新时,用service实现,以从阿里云上下载为例:

public  void downloadFile(Context context,final File file,String fileobjectkey) {


// 明文设置secret的方式建议只在测试时使用,更多鉴权模式请参考后面的`访问控制`章节

OSSCredentialProvider credentialProvider =new OSSPlainTextAKSKCredentialProvider(

accessKeyId,accessKeySecret);

OSSClient oss = new OSSClient(context,endpoint, credentialProvider);

// 构造下载文件请求

GetObjectRequest get = new GetObjectRequest(bucketName, fileobjectkey);

try {

// 同步执行下载请求,返回结果

GetObjectResult getResult = oss.getObject(get);

// 获取文件输入流

InputStream inputStream = getResult.getObjectContent();

int total = (int)getResult.getContentLength();

            FileOutputStream fileOutputStream = new FileOutputStream(file); 


            byte[] buf = newbyte[1024]; 

            int ch = -1; 

            int count = 0; 

            int showindex = 5;

            while ((ch = inputStream.read(buf)) != -1) {

                fileOutputStream.write(buf, 0, ch); 

                count += ch; 

                if (count*100/total>=showindex) {

                updateNotification.setLatestEventInfo(updateService.this,"项目名称",showindex + "%",updatePendingIntent);

                updateNotificationManager.notify(0,updateNotification);

                showindex += 5;

}

            }

        fileOutputStream.flush(); //关键语句--解决了下载后的apk解析错误问题;

        if (fileOutputStream !=null) { 

            fileOutputStream.close(); 

        }

updateNotification.setLatestEventInfo(updateService.this,"项目名称","100%",updatePendingIntent);

updateNotificationManager.notify(0,updateNotification);

// 关闭输入流等

fileOutputStream.close();

inputStream.close();

stopSelf();

//关闭这这service

Message message = updateHandler.obtainMessage();

message.obj = file;

message.what =DOWNLOAD_COMPLETE;

updateHandler.sendMessage(message);

} catch (Exception e) {

// 本地异常如网络异常等

e.printStackTrace();

//关闭这这service

Message message = updateHandler.obtainMessage();

message.obj = file;

message.what =DOWNLOAD_FAIL;

updateHandler.sendMessage(message);

}


猜你喜欢

转载自blog.csdn.net/woyaoxianzaixiazai/article/details/52327686