使用jsoup和asynctask下载管理器下载多个文件,没有发生

时间:2014-04-22 17:36:56

标签: android android-asynctask jsoup

这是我的代码: -

public class grabber extends Activity 
{


int counter;
String folderPath;
String[] array;
DownloadManager dm;
private long enqueue;

public void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.data);

    Down t = new Down();
    t.execute();




}


private class Down extends AsyncTask<String, Void, String> 
{
    protected String doInBackground(String... params)
    {
        Log.i("grabber", "in back");
String   w =Environment.getExternalStorageDirectory().getAbsoluteFile()+"/Android/data/myfolder";
    createdir(w);


    String link = "http://mywebsitehere.com";


    Document doc;

      array = new String[200];
    try {

        doc = Jsoup.connect(link).get();
        String title = doc.title();


         folderPath = w+ File.separator+title;

         createdir(folderPath);


        Elements images = doc.select("img[src~=(?i)\\.(png|jpe?g|gif)]");
         counter =0;

        for (Element image : images) 
        {
             String img = image.attr("src");
            array[counter]=img;

            counter++;
        }

    } catch (IOException e) 
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return null;
}


    protected void onPostExecute(String result) 
    {   

        Toast.makeText(getApplicationContext(), 
          "done", Toast.LENGTH_SHORT).show();

        for(int i=0;i<counter;i++)
        {
            dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
            Request request = new Request(
                    Uri.parse(array[i]));
            request.setDescription("Android Data download using DownloadManager.");
              request.setDestinationInExternalFilesDir(getApplicationContext(),folderPath,File.separator+"pic"+Integer.toString(i)+".jpg");
            enqueue = dm.enqueue(request);



        }


    }
 }




public void createdir(String Path)
{
File file = new File(Path);
    if(!file.exists())
    {
        file.mkdirs();

    }

}
}

它应该做什么: -     它应该将包含图像的给定链接下载到给定路径。

它的作用: -        该应用程序运行得很好,我的UI没有挂起。几秒后“完成”显示Toast,这意味着asynctask已完成,我们在onPostExecute。但当我检查目录时,我发现Android/data/myfolder内没有文件夹。 主要的挫折是有时它起作用,即图像被下载,有时不被下载。

所以我猜它可能是因为一些http超时或一些我无法正确处理的错误,因为我在createdir(folderPath);之后使用Jsoup并且错误发生在那里所以没有文件夹得到在那里创造。

任何想法!??在此先感谢。

编辑: - 我在jsoup.connect(link).get();

期间得到SocketTimeoutException

2 个答案:

答案 0 :(得分:0)

您必须将以下权限添加到应用程序的清单中,才能写入外部存储。

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

我希望你这样做?

答案 1 :(得分:0)

最后,我做了一些试验和错误。

我们可以在这里使用超时选项通过更改

来减少 Sockettimeoutexception
        doc = Jsoup.connect(link).get();

        doc = Jsoup.connect(link).timeout(10000).get();

还有一个错误,那就是删除 onPostExecute 中的Toast消息,因为我们无法在没有处理程序从后台任务到UI的情况下进行交互。

那就是它。

相关问题