下載一個網路檔案的函數如下
public static File downLoadFile(String httpUrl) {<br /> // TODO Auto-generated method stub<br /> final String fileName = "nq.apk";<br /> File tmpFile = new File("//sdcard");<br /> if (!tmpFile.exists()) {<br /> tmpFile.mkdir();<br /> }<br /> final File file = new File("//sdcard//" + fileName);<br /> try {<br /> URL url = new URL(httpUrl);<br /> try {<br /> HttpURLConnection conn = (HttpURLConnection) url<br /> .openConnection();<br /> InputStream is = conn.getInputStream();<br /> FileOutputStream fos = new FileOutputStream(file);<br /> byte[] buf = new byte[256];<br /> conn.connect();<br /> double count = 0;<br /> if (conn.getResponseCode() >= 400) {<br />// Toast.makeText(DownFile.this, "連線逾時", Toast.LENGTH_SHORT)<br />// .show();<br /> Log.i("time","time exceed");<br /> } else {<br /> while (count <= 100) {<br /> if (is != null) {<br /> int numRead = is.read(buf);<br /> if (numRead <= 0) {<br /> break;<br /> } else {<br /> fos.write(buf, 0, numRead);<br /> }<br /> } else {<br /> break;<br /> }<br /> }<br /> }<br /> conn.disconnect();<br /> fos.close();<br /> is.close();<br /> } catch (IOException e) {<br /> // TODO Auto-generated catch block<br /> e.printStackTrace();<br /> }<br /> } catch (MalformedURLException e) {<br /> // TODO Auto-generated catch block<br /> e.printStackTrace();<br /> }<br /> return file;<br />}
如果是一個apk檔案,開啟並且安裝的函數為
private void openFile(File file) {<br /> // TODO Auto-generated method stub<br /> Log.e("OpenFile", file.getName());<br /> Intent intent = new Intent();<br /> intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);<br /> intent.setAction(android.content.Intent.ACTION_VIEW);<br /> intent.setDataAndType(Uri.fromFile(file),<br /> "application/vnd.android.package-archive");<br /> startActivity(intent);<br />}
這樣就可以實現一個apk檔案的下載和安裝,後續有時間給大家介紹下靜默安裝和卸載的實現
本文地址http://blog.csdn.net/Zengyangtech/archive/2011/03/15/6251377.aspx
轉載請註明