简体   繁体   中英

Android File download to sdcard not working

i am the android app developer newbie !

I have a new question .

i have in my MainActivity class this void which is called once a user clicks a checkbox , what it does is basically download a file on the web to the a folder called test in the external storage i added nessacry permissions inside AndroidManifest.xml (is there aa way to download the file to internal storage) but its giving an fc in runtime here is part of the log ...

LOG

D/DownloadManager(14956): download begining
D/DownloadManager(14956): download url:http://forum.xda-developers.com/attachment.php?attachmentid=2109443&d=1373572809l

D/DownloadManager(14956): downloaded file name:X-Reality_Engine.zipA
D/AndroidRuntime(14956): Shutting down VM
W/dalvikvm(14956): threadid=1: thread exiting with uncaught exception (group=0x4
1dc0ce0)
I/Process (14956): Sending signal. PID: 14956 SIG: 9
I/ActivityManager(23309): Process com.mythi.tests (pid 14956) has died.

MainActivity.java

   public void onCheckboxClicked5(View view) {

    String DownloadUrl = "http://forum.xda-developers.com/attachment.php?attachmentid=2109443&d=1373572809";
    String fileName = "X-Reality_Engine.zip";

        // Is the view now checked?
        boolean checked5 = ((CheckBox) view).isChecked();

        // Check which checkbox was clicked
        switch(view.getId()) {
            case R.id.checkBox5:
                PreferenceManager.getDefaultSharedPreferences(this).edit()
                .putBoolean("checkBox5", checked5).commit();
                if (checked5){
                    try {
                        File root = android.os.Environment.getExternalStorageDirectory();               

                        File dir = new File (root.getAbsolutePath() + "/test");
                        if(dir.exists()==false) {
                             dir.mkdirs();
                        }

                        URL url = new URL(DownloadUrl); //you can write here any link
                        File file = new File(dir, fileName);

                        long startTime = System.currentTimeMillis();
                        Log.d("DownloadManager", "download begining");
                        Log.d("DownloadManager", "download url:" + url);
                        Log.d("DownloadManager", "downloaded file name:" + fileName);

                        /* Open a connection to that URL. */
                        URLConnection ucon = url.openConnection();

                        /*
                         * Define InputStreams to read from the URLConnection.
                         */
                        InputStream is = ucon.getInputStream();
                        BufferedInputStream bis = new BufferedInputStream(is);

                        /*
                         * Read bytes to the Buffer until there is nothing more to read(-1).
                         */
                        ByteArrayBuffer baf = new ByteArrayBuffer(5000);
                        int current = 0;
                        while ((current = bis.read()) != -1) {
                           baf.append((byte) current);
                        }


                        /* Convert the Bytes read to a String. */
                        FileOutputStream fos = new FileOutputStream(file);
                        fos.write(baf.toByteArray());
                        fos.flush();
                        fos.close();
                        Log.d("DownloadManager", "download ready in" + ((System.currentTimeMillis() - startTime) / 1000) + " sec");

                } catch (IOException e) {
                    Log.d("DownloadManager", "Error: " + e);
                }

             }

It's not said in your log but I see that you are not using a separate thread for network access. This is invalid situation and your application will crash. You have to create a separate thread to download the file from web. SEE THIS Android docs

Add this code to your onCLick button, or whatever button or row u will click to get download..

public void downloadFile(){
    String DownloadUrl = "Paste Url to download a pdf file here…";
    DownloadManager.Request request = new DownloadManager.Request(Uri.parse(DownloadUrl));
    request.setDescription("sample pdf file for testing");   //appears the same in Notification bar while downloading

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        request.allowScanningByMediaScanner();
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
    }
    request.setDestinationInExternalFilesDir(getApplicationContext(),null, "whatevernameoffileuwant.extensionoffilw");
//request.setDestinationInExternalFilesDir(getApplicationContext(),null,  "Sample.pdf");
    // get download service and enqueue file
    DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
    manager.enqueue(request);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM