Android 下載一個檔案以及開啟這個apk檔案

來源:互聯網
上載者:User

下載一個網路檔案的函數如下

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

轉載請註明

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.