3

I have been stuck for days when developing a function that allow user to check for new app update (I use local server as my distribution point). The problem is the downloading progress seems working perfectly but I could not find the downloaded file anywhere in my phone (i have no sd card / external memory). Below is what i have came so far.

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

}

After the progress dialog reach 100% and dismissed, I could not find the file. I assume that's the reason application cannot continue install downloaded apk.

Did I miss some code ?

Raedwald
  • 46,613
  • 43
  • 151
  • 237
Rudy Rudy
  • 125
  • 1
  • 6
  • What's the value for `file_url`? – Rohit5k2 Nov 19 '18 at 08:16
  • The internal storage means a secure place inside your package. but, external means Phone storage and sd card(Not secure). Just noting since "(i have no sd card / external memory)" https://www.youtube.com/watch?v=oIn0MZQJpp0 – Mohammad Tabbara Nov 19 '18 at 08:31
  • @Rohit5k2 variable file_url will receipt returned value from function doInBackground. So the value will be getFilesDir() + "/myapp.apk" – Rudy Rudy Nov 19 '18 at 09:10
  • https://meta.stackoverflow.com/questions/326569/under-what-circumstances-may-i-add-urgent-or-other-similar-phrases-to-my-quest – Raedwald Dec 21 '18 at 14:58

2 Answers2

7

I can not believe i solved this. What I do is replacing:

getFilesDir()

to

Environment.getExternalStorageDirectory()

below I post my final code

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

}

Simply put this code to use this class

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

This code can perform file download to your internal phone storage with a progress bar and continue asking your permission for application install.

Enjoy it.

Rudy Rudy
  • 125
  • 1
  • 6
0

as we know getFilesDir() returns the absolute path to the directory on the filesystem where files created, which will give you path /data/data/your package/files

so you can find the file(if downloaded completely) there

i suggest you to read this article:

How to get the each directory path

Farrokh
  • 1,167
  • 1
  • 7
  • 18
  • The path will be /data/user/0/package/files/. But after the download process finished, the file is not there (i have searched my entire internal phone memory) – Rudy Rudy Nov 19 '18 at 09:13
  • the file stored in application data folder, it means `/data/data/your package/files`, not the ` /data/user/0/package/files/`, check there, i hope you will find your file there – Farrokh Nov 20 '18 at 05:48
  • 1
    there is no folder /data/data. I wonder if somwthing is wrong with my code. Please have a look. – Rudy Rudy Nov 20 '18 at 12:25