Android下载服务:获取空文件

时间:2014-04-18 09:48:18

标签: android service download

我正在尝试创建一个服务,从我的本地网络中的服务器下载文件。每个人认为似乎没问题,服务启动,下载结束时,当我在SD卡中检查文件时发现一个emty文件,有人可以帮我解决这个问题,提前谢谢你。

这是服务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:我加入了corse的权限,服务器可以ping通手机,wamp服务器开启。

1 个答案:

答案 0 :(得分:1)

尝试将文件存储在外部存储设备中。

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

然后

 OutputStream output = new FileOutputStream(mFile,true);