【问题标题】:Android Dowload Service :getting empty fileAndroid下载服务:获取空文件
【发布时间】:2014-04-18 09:48:17
【问题描述】:

我正在尝试创建一个服务来从我的本地网络中的服务器下载文件。每个想法似乎都很好,服务启动,当下载结束时,当我检查 sdcard 中的文件时找到了一个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:我添加了权限,服务器可以ping到手机,wamp服务器是ON的。

【问题讨论】:

  • 您没有在 doInBackground() 中返回文件路径。你只返回null。
  • 感谢您的回复。所以它应该返回什么? @Yuvaraja
  • 对不起!我想你会在执行后考虑文件路径。你没有考虑返回的文件路径。

标签: android service download


【解决方案1】:

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

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

然后

 OutputStream output = new FileOutputStream(mFile,true);

【讨论】:

  • **edit **当我使用大小 = 107 Ko 的 pdf 时,我有这个日志Error***:(26880): divide by zero,但是当我尝试另一个同名但大小 = 4,88 Mo 时,我有这个 LOG = 04-18 12:03:58.743: E/Error***:(24424): length=163; index=163 @Yuvaraja 你说它是从哪里来的?代码中有一行 `InputStream input = new BufferedInputStream(url.openStream(), 8192);` 也许这行会导致问题。谢谢。
  • 你可以发布堆栈跟踪吗?
猜你喜欢
  • 2016-05-28
  • 1970-01-01
  • 1970-01-01
  • 2017-10-18
  • 2015-02-26
  • 1970-01-01
  • 2021-08-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多