public void downloadUpdateFile(String downloadUrl, String saveFile) throws Exception {
int bytesum = 0;
int byteread = 0;
URL url = new URL(downloadUrl);
try {
URLConnection conn = url.openConnection();
InputStream inStream = conn.getInputStream();
File file = new File("/data/data/com.example.updatetest/files/"+saveFile);
Runtime.getRuntime().exec("chmod 777 "+ file);
FileOutputStream fs = new FileOutputStream(file);
//getApplicationContext().openFileOutput(saveFile, getApplicationContext().MODE_APPEND);
byte[] buffer = new byte[1204];
int length;
while ((byteread = inStream.read(buffer)) != -1) {
bytesum += byteread;
System.out.println(bytesum);
fs.write(buffer, 0, byteread);
}
installApk();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}}
public void installApk(){
Intent i = new Intent(Intent.ACTION_VIEW);
String filePath = "/data/data/com.example.updatetest/files/ModuleTest.apk";
i.setDataAndType(Uri.parse("file://" + filePath),"application/vnd.android.package-archive");
// i.setDataAndType(
// Uri.parse("file:///data/data/com.example.updatetest/files/yuehe.mpg"),
// "video/mp4");
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
}
记得加上网络和读写的权限:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.INSTALL_PACKAGES"/>
<uses-permission android:name="android.permission.GET_TASKS"/>
<uses-permission android:name="android.permission.INSTALL_LOCATION_PROVIDER"/>
原文:http://www.cnblogs.com/moreking/p/4312214.html