将Android应用程序的APK文件下载并保存到内部存储

3

在开发一个允许用户检查新的应用程序更新的功能时,我卡了好几天(我使用本地服务器作为分发点)。问题在于下载进度似乎完美运行,但我找不到已下载的文件在我的手机上的任何位置(我的手机没有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的原因。

我错过了一些代码吗?


file_url 的值是什么? - Rohit5k2
内部存储意味着您包装内的一个安全位置,而外部存储则指手机存储和SD卡(不安全)。只是提醒一下,因为"(我没有SD卡/外部存储)"。https://www.youtube.com/watch?v=oIn0MZQJpp0 - Mohammad Tabbara
@Rohit5k2 变量 file_url 将接收 doInBackground 函数返回的值。因此,该值将为 getFilesDir() + "/myapp.apk"。 - Rudy Rudy
https://meta.stackoverflow.com/questions/326569/under-what-circumstances-may-i-add-urgent-or-other-similar-phrases-to-my-quest - Raedwald
2个回答

7

我简直不敢相信我解决了这个问题。 我的做法是将以下内容替换:

getFilesDir()

to

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");

这段代码可以带有进度条的方式将文件下载到您的手机内部存储,并继续请求应用程序安装权限。祝使用愉快。

1
但是,这不是内部存储。你要保存在外部存储中。 - Rougher
这怎么能回答你的问题呢?将数据保存到外部存储并不是一个问题。 - Itay Feldman

0

正如我们所知,getFilesDir()返回创建的文件在文件系统中的绝对路径,这将给出路径/data/data/your package/files

因此,您可以在那里找到该文件(如果已完全下载)

我建议您阅读这篇文章:

如何获取每个目录的路径


路径将会是/data/user/0/package/files/。但是在下载过程完成后,文件并不在那里(我已经搜索了整个内部手机存储)。 - Rudy Rudy
文件存储在应用程序数据文件夹中,即/data/data/your package/files,而不是/data/user/0/package/files/。请检查那里,希望你能在那里找到你的文件。 - Farrokh
1
没有/data/data文件夹。我想知道我的代码有没有问题。请帮忙看一下。 - Rudy Rudy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接