簡體   English   中英

Android下載apk文件並保存到內部存儲

[英]Android download apk file and save to INTERNAL STORAGE

在開發允許用戶檢查新應用程序更新的功能時,我已經停留了幾天(我使用本地服務器作為分發點)。 問題是下載進度似乎工作正常,但我在手機的任何位置都找不到下載的文件(我沒有SD卡/外部存儲器)。 以下是我到目前為止所取得的成就。

 class DownloadFileFromURL extends AsyncTask<String, String, String> {
    ProgressDialog pd;
    String path = getFilesDir() + "/myapp.apk";
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pd = new ProgressDialog(DashboardActivity.this);
        pd.setTitle("Processing...");
        pd.setMessage("Please wait.");
        pd.setMax(100);
        pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        pd.setCancelable(true);
        //pd.setIndeterminate(true);
        pd.show();

    }

    /**
     * Downloading file in background thread
     * */
    @Override
    protected String doInBackground(String... f_url) {
        int count;

        try {

            URL url = new URL(f_url[0]);
            URLConnection conection = url.openConnection();
            conection.connect();

            // download the file
            InputStream input = new BufferedInputStream(url.openStream());
            OutputStream output = new FileOutputStream(path);

            byte data[] = new byte[1024];

            long total = 0;

            while ((count = input.read(data)) != -1) {
                total += count;
                publishProgress("" + (int) ((total * 100) / lenghtOfFile));

                // writing data to file
                output.write(data, 0, count);
            }

            // flushing output
            output.flush();
            // closing streams
            output.close();
            input.close();

        } catch (Exception e) {
            Log.e("Error: ", e.getMessage());
        }
        return path;
    }

    protected void onProgressUpdate(String... progress) {
        pd.setProgress(Integer.parseInt(progress[0]));
    }

    @Override
    protected void onPostExecute(String file_url) {
        // dismiss the dialog after the file was downloaded
        if (pd!=null) {
            pd.dismiss();
        }
    // i am going to run the file after download finished
        StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
        StrictMode.setVmPolicy(builder.build());

        Intent i = new Intent(Intent.ACTION_VIEW);

        i.setDataAndType(Uri.fromFile(new File(file_url)), "application/vnd.android.package-archive" );
        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        Log.d("Lofting", "About to install new .apk");

        getApplicationContext().startActivity(i);
    }

}

進度對話框達到100%並關閉后,我找不到文件。 我認為這就是應用程序無法繼續安裝下載的APK的原因。

我錯過了一些代碼嗎?

我不敢相信我解決了這個問題。 我要做的是替換:

getFilesDir()

Environment.getExternalStorageDirectory()

下面我發布我的最終代碼

    class DownloadFileFromURL extends AsyncTask<String, String, String> {
    ProgressDialog pd;
    String pathFolder = "";
    String pathFile = "";

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pd = new ProgressDialog(DashboardActivity.this);
        pd.setTitle("Processing...");
        pd.setMessage("Please wait.");
        pd.setMax(100);
        pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        pd.setCancelable(true);
        pd.show();
    }

    @Override
    protected String doInBackground(String... f_url) {
        int count;

        try {
            pathFolder = Environment.getExternalStorageDirectory() + "/YourAppDataFolder";
            pathFile = pathFolder + "/yourappname.apk";
            File futureStudioIconFile = new File(pathFolder);
            if(!futureStudioIconFile.exists()){
                futureStudioIconFile.mkdirs();
            }

            URL url = new URL(f_url[0]);
            URLConnection connection = url.openConnection();
            connection.connect();

            // this will be useful so that you can show a tipical 0-100%
            // progress bar
            int lengthOfFile = connection.getContentLength();

            // download the file
            InputStream input = new BufferedInputStream(url.openStream());
            FileOutputStream output = new FileOutputStream(pathFile);

            byte data[] = new byte[1024]; //anybody know what 1024 means ?
            long total = 0;
            while ((count = input.read(data)) != -1) {
                total += count;
                // publishing the progress....
                // After this onProgressUpdate will be called
                publishProgress("" + (int) ((total * 100) / lengthOfFile));

                // writing data to file
                output.write(data, 0, count);
            }

            // flushing output
            output.flush();

            // closing streams
            output.close();
            input.close();


        } catch (Exception e) {
            Log.e("Error: ", e.getMessage());
        }

        return pathFile;
    }

    protected void onProgressUpdate(String... progress) {
        // setting progress percentage
        pd.setProgress(Integer.parseInt(progress[0]));
    }

    @Override
    protected void onPostExecute(String file_url) {
        if (pd!=null) {
            pd.dismiss();
        }
        StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
        StrictMode.setVmPolicy(builder.build());
        Intent i = new Intent(Intent.ACTION_VIEW);

        i.setDataAndType(Uri.fromFile(new File(file_url)), "application/vnd.android.package-archive" );
        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        getApplicationContext().startActivity(i);
    }

}

只需將這段代碼用於此類

new DownloadFileFromURL().execute("http://www.yourwebsite.com/download/yourfile.apk");

此代碼可以使用進度條將文件下載到內部電話存儲中,並繼續征求您對應用程序安裝的許可。

好好享受。

我們知道getFilesDir()返回創建文件的文件系統上目錄的絕對路徑,這將為您提供/data/data/your package/files路徑

這樣您就可以在那里找到文件(如果已完全下載)

我建議您閱讀這篇文章:

如何獲取每個目錄路徑

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM