【问题标题】:Android download apk file and save to INTERNAL STORAGEAndroid下载apk文件并保存到INTERNAL STORAGE
【发布时间】:2018-11-19 08:15:26
【问题描述】:

在开发允许用户检查新应用程序更新的功能时,我被困了好几天(我使用本地服务器作为我的分发点)。 问题是下载进度看起来很完美,但我在手机的任何地方都找不到下载的文件(我没有 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 的值是多少?
  • 内部存储意味着您包裹内的安全位置。但是,外部意味着手机存储和 SD 卡(不安全)。只是注意到“(我没有 sd 卡/外部存储器)”youtube.com/watch?v=oIn0MZQJpp0
  • @Rohit5k2 变量 file_url 将接收来自函数 doInBackground 的返回值。所以值将是 getFilesDir() + "/myapp.apk"

标签: android android-internal-storage downloadfileasync


【解决方案1】:

我不敢相信我解决了这个问题。 我所做的是替换:

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

此代码可以使用进度条将文件下载到您的手机内部存储,并继续询问您是否允许安装应用程序。

尽情享受吧。

【讨论】:

  • 但是,它不是内部存储。您保存在外部存储中。
  • 这是您问题的答案吗?保存到外部存储不是问题..
【解决方案2】:

我们知道getFilesDir()返回文件系统上创建文件的目录的绝对路径,这将为您提供路径/data/data/your package/files

这样你就可以在那里找到文件(如果完全下载的话)

我建议你阅读这篇文章:

How to get the each directory path

【讨论】:

  • 路径将是 /data/user/0/package/files/。但下载过程完成后,文件不存在(我已经搜索了我的整个手机内存)
  • 存储在应用程序数据文件夹中的文件,它表示/data/data/your package/files,而不是`/data/user/0/package/files/`,检查那里,希望你能在那里找到你的文件
  • 没有文件夹 /data/data。我想知道我的代码是否有问题。请看一看。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-05
  • 1970-01-01
  • 1970-01-01
  • 2023-03-27
  • 2022-01-15
  • 2012-01-10
相关资源
最近更新 更多