android 從服務器上獲取APK並下載安裝


 
簡單的為新手做個分享。     網上有些資料,不過都是很零散,或是很亂的,有的人說看不懂。    一直有新手說 做到服務器更新APK時沒有思路,這里做個簡單的分享,希望有不同思路的可以討論。     下面做個很簡單的讀取處理和講解思路。     代碼帶有注釋 

 

 try {  
            URL url = new URL(params[0]);  
            HttpURLConnection connection = (HttpURLConnection) url  
                    .openConnection();  
            connection.setConnectTimeout(10 * 1000); //超時時間 
            connection.connect();  //連接
            if (connection.getResponseCode() == 200) { //返回的響應碼200,是成功. 
                File file = new File("/mnt/sdcard/yang/dujinyang.apk");   //這里我是手寫了。建議大家用自帶的類
                file.createNewFile();  
                InputStream inputStream = connection.getInputStream();  
                ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream(); //緩存 
                byte[] buffer = new byte[1024 * 10];  
                while (true) {  
                   int len = inputStream.read(buffer);  
                   publishProgress(len);  
                    if (len == -1) {  
                        break;  //讀取完
                    }  
                   arrayOutputStream.write(buffer, 0, len);  //寫入
                }  
                arrayOutputStream.close();  
                inputStream.close();  
 
                byte[] data = arrayOutputStream.toByteArray();  
                FileOutputStream fileOutputStream = new FileOutputStream(file);  
                fileOutputStream.write(data); //記得關閉輸入流 
                fileOutputStream.close();  
            }  
  
        } catch (MalformedURLException e) {  
.            e.printStackTrace();  
       } catch (IOException e) {  
            e.printStackTrace();  
        }  


 

 

 以上是讀取APK文件並保存在了本地,InputStream轉為FileOutputStream保存HttpURLConnection獲取到的數據 。
 那么只要再找到你的那個保存的路徑就能實現安裝了。
  
   

下面是安裝和卸載的代碼:  
首先說下卸載:Uri packageURI = Uri.parse("package:com.demo.DUJINYANG");  
 Intent uninstallIntent = new Intent(Intent.ACTION_DELETE, packageURI);   
startActivity(uninstallIntent);Environment擁有一些可以獲取環境變量的方法 
package:com.demo.DUJINYANG  這個形式是 package:程序完整的路徑 (包名+程序名). 
 
然后是 --安裝: String str = "/Dujinyang.apk"; //APK的名字
String fileName = Environment.getExternalStorageDirectory() + str;   
//我們上面說到路徑Intent intent = new Intent(Intent.ACTION_VIEW);  
intent.setDataAndType(Uri.fromFile(new File(fileName)), "application/vnd.android.package-archive");
 startActivity(intent); 
 
主要代碼如下://打開APK程序代碼

private void openFiles(File file) {
                // TODO Auto-generated method stub
                Intent intent = new Intent();
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.setAction(android.content.Intent.ACTION_VIEW);
                intent.setDataAndType(Uri.fromFile(file),
                                "application/vnd.android.package-archive");
                startActivity(intent);
        }  
 
當然拉 ,這里不僅一種方法:以下方法也是可行的--
//下載apk程序代碼
protected File downLoadFile(String httpUrl) {
                final String fileName = "dujinyang.apk";
                File tmpFile = new File("/sdcard/update");
                if (!tmpFile.exists()) {
                        tmpFile.mkdir();//創建文件夾
                }
                final File file = new File("/sdcard/update/" + fileName);

                try {
                        URL url = new URL(httpUrl);
                        try {
                                HttpURLConnection conn = (HttpURLConnection) url
                                                .openConnection();
                                InputStream is = conn.getInputStream();
                                FileOutputStream fileOutput= new FileOutputStream(file);
                                byte[] buf = new byte[256];//分配byte
                                conn.connect();
                                double count = 0;
                                if (conn.getResponseCode() >= 400) {
                                        Toast.makeText(Main.this, "連接超時", Toast.LENGTH_SHORT)
                                                        .show();
                                } else {
                                        while (count <= 100) {
                                                if (is != null) {
                                                        int numRead = is.read(buf);
                                                        if (numRead <= 0) {
                                                                break;
                                                        } else {
                                                                fileOutput.write(buf, 0, numRead);
                                                        }

                                                } else {
                                                        break;
                                                }

                                        }
                                }

                                conn.disconnect();//需要記得關閉連接
                                fileOutput.close();
                                is.close();
                        } catch (IOException e) {
                                e.printStackTrace();
                        }
                } catch (MalformedURLException e) { 	                      e.printStackTrace();
                }

                return file;
        }


 

 

到這里 思路簡單的理清 完了。
 
 此時可以根據你自身的項目去整改。如果新手還有不懂的可以私聊。
 
 --分享 希望大家有好的代碼可以分享,共同討論

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM