下载app 并安装

下载

private void downloadApp() {
new Thread(new Runnable() {  
  @Override     
public void run() {         
URL url = null;         
InputStream in = null;        
FileOutputStream out = null;      
 HttpURLConnection conn = null;           
  try {             
 url = new URL(spec);              
 conn = (HttpURLConnection) url.openConnection();       
conn.connect();            
long fileLength = conn.getContentLength();            
in = conn.getInputStream();          
  File filePath = new File(FILE_PATH);         
   if (!filePath.exists()) {         
       filePath.mkdir();           
 }              
out = new FileOutputStream(new File(FILE_NAME));               
byte[] buffer = new byte[1024];   
         int len = 0;     
       long readedLength = 0l;             
 while ((len = in.read(buffer)) != -1) {              
  // 用户点击“取消”按钮,下载中断              
  if (isCancel) {                     
 break;               
 }                
  out.write(buffer, 0, len);               
 readedLength += len;            
    curProgress = (int) (((float) readedLength / fileLength) * 100);                    handler.sendEmptyMessage(UPDARE_TOKEN);      
          if (readedLength >= fileLength) {              
      progressDialog.dismiss();                        // 下载完毕,通知安装                        handler.sendEmptyMessage(INSTALL_TOKEN);               
     break;              
  }            
}              
out.flush();      
  } catch (Exception e) {   
         e.printStackTrace();          
} finally {          
  if (out != null) {          
      try {                      
 out.close();                
} catch (IOException e) {             
       e.printStackTrace();           
     }              
}             
 if (in != null) {            
    try {                   
 in.close();               
 } catch (IOException e) {      
              e.printStackTrace(); 
               }              
}                
 if (conn != null) {                  
 conn.disconnect();         
     }       
  }     
 }   
}).start();
 }

安装

 private void installApp() {   
 File appFile = new File(FILE_NAME);  
 if (!appFile.exists()) {  
    return;    }    
// 跳转到新版本应用安装页面  
 Intent intent = new Intent(Intent.ACTION_VIEW);    
 intent.setDataAndType(Uri.parse("file://" + appFile.toString()), "application/vnd.android.package-archive");   
 context.startActivity(intent);}

你可能感兴趣的:(下载app 并安装)