Amina
Amina

Reputation: 723

Android Dowload Service :getting empty file

I'm tryinig to create a service to download a file from a server, in my local network.Every think seems to be ok ,the service starts, when the download ends ,when i check for the file in the sdcard i found an emty file ,can someone help me to solve this problem ,Thank you in advance.

This the service DownloadService :

public class DownloadService extends Service{

 private static String file_url = "http://192.168.1.150:8080/TestAndroid/DownloadServlet/Desert.pdf";
    public int onStartCommand(Intent intent, int flags, int startId) {
         Toast.makeText(getBaseContext(), "Service started", Toast.LENGTH_LONG).show();
         new DownloadFileFromURL().execute(file_url);//Appel vers Asynctask 

        return START_STICKY;

    }

    /**
     * Background Async Task to download file
     * */
    class DownloadFileFromURL extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread
         * Show Progress Bar Dialog
         * */

        public String[] listDebitDown = new String[163] ;
        int compteur = 0;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
           // showDialog(progress_bar_type);
        }

        /**
         * 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();
                // this will be useful so that you can show a tipical 0-100% progress bar
                int lenghtOfFile = conection.getContentLength();

                // download the file
                InputStream input = new BufferedInputStream(url.openStream(), 8192);

                // Output stream
                OutputStream output = new FileOutputStream("/sdcard/downloadedfile.pdf");//jpg
                int  nombrePaquets ;
                nombrePaquets = (lenghtOfFile / 1024 ) + (lenghtOfFile % 1024 );
                byte data[] = new byte[1024];

                String tabResult [] = new String [nombrePaquets];

                long total = 0;
                long startTotalTime = System.currentTimeMillis();
                long passedTime =0;
             // Get ListView object from xml
             //   listView = (ListView) findViewById(R.id.listView1);

                while ((count = input.read(data)) != -1) {
                    total += count;



                    // 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 null;
        }

        /**
         * After completing background task
         * Dismiss the progress dialog
         * **/
        @Override
        protected void onPostExecute(String file_url) {

            Toast.makeText(getApplicationContext(),
                    "téléchargement términé " , Toast.LENGTH_LONG)
                    .show();
            Toast.makeText(getApplicationContext(),
                    "Passagr "+ listDebitDown[10] , Toast.LENGTH_LONG)
                    .show();

            // Displaying downloaded image into image view
            // Reading image path from sdcard
            String imagePath = Environment.getExternalStorageDirectory().toString() + "/downloadedfile.pdf";//jpg
            Log.i("imagePath", imagePath);
            Log.i("isExternalStorageWritable", isExternalStorageWritable() + "true" );

        }

    }
    public boolean isExternalStorageWritable() {
        String state = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(state)) {
            Log.i("isExternalStorageWritable", "true" );
            return true;
        }
        return false;
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }

}

PS:of corse i added permission ,the server can ping to the phone ,the wamp server is ON .

Upvotes: 1

Views: 290

Answers (1)

Yuvaraja
Yuvaraja

Reputation: 715

Try to store file in external storage.

File mFile= new File(Environment.getExternalStorageDirectory(), "downloadedfile.pdf");
if(!mFile.isExist()){
mFile.createNewFile();
}

then

 OutputStream output = new FileOutputStream(mFile,true);

Upvotes: 1

Related Questions