1

所以我有一个我正在开发的小应用程序,它可以从网络上抓取漫画并将它们显示在我的手机上。没什么花哨的,只是用它来学习绳索。调用comicReload()的函数;完成大部分工作,它在应用程序中被多次调用(第一次运行时,以及当用户单击某些按钮时。这是函数:

public void comicReload () throws IOException {
    //clears some Vectors that have things in them from the last run
    imagetitles.clear();
    imagetext.clear();
    imagelinks.clear();

    //forms the link it will connect to, and connects
    connector = siteBase + Integer.toString(comicNumber);
    doc = Jsoup.connect(connector).get();
    media = doc.select("[src]");

    //gets the required media from the site
    for (Element src : media) {
        if (src.tagName().equals("img"));
            imagetitles.add(src.attr("alt"));
            imagetext.add(src.attr("title"));
            imagelinks.add(src.attr("src"));
    }

    //some variables I could probably get rid of, but it's easy to read
    Integer titlesize = imagetitles.size();
    Integer textsize = imagetext.size();
    Integer linkssize = imagelinks.size();

    comicTitle = (imagetitles.get(titlesize-4));
    hoverText = (imagetext.get(textsize-4));
    comicLink = (imagelinks.get(linkssize-4));

    //gets the picture I am looking for along with the associated text
    URL url = new URL(comicLink);
    InputStream is = (InputStream) url.getContent();
    image = Drawable.createFromStream(is, "src name");

    //finally puts the scraped information into the layout
    comicView.setImageDrawable(image);
    title.setText(comicTitle);
    htext.setText(hoverText);
}

它在被调用时可以 100% 正常工作,但它在 3G 上有点慢,所以我尝试添加一个 ProgressDialog 以在加载时显示。这是我的尝试(这是在我以前只有 comicReload(); 的地方运行的代码)

pd = ProgressDialog.show(this, "Getting Comic", "Loading", true, false);
    new Thread(new Runnable() {  
           public void run() {
               try {
                   comicReload();
               } catch (IOException e) {
                   Log.i("ComicReloadFail","Sam");
               }
               pd.dismiss();
               return;
           }
    }).start();

线程本身运行良好,当我使用 ComicReload() 放置一些随机代码来代替 try-catch 块时执行;在其中一切都变得花花公子。第二次我将 ComicReload() 放回那里,但是,运行应用程序会导致 ProgressDialog 微调器在应用程序强制关闭之前旋转几秒钟。这是什么原因造成的?以及为什么comicReload()在线程中时会停止工作。我只想要一种方法来执行该方法,并在其工作时使用微调器。

在此先感谢各位,我知道要阅读的内容很多。

4

2 回答 2

1

您不能在与创建 UI 的线程不同的线程中进行 UI 相关更新。

尝试使用处理程序

public static final Handler handlerVisibility = new Handler() {
    public void handleMessage(Message msg) {
        int visibility = msg.getData().getInt("visibility");
        view.setVisibility(visibility);
    }
};
于 2010-12-09T02:57:21.870 回答
1

你不能在工作线程中做任何与 UI 相关的事情。您需要在 UI 线程上执行此操作。有一些简单的方法可以做到这一点 -Activity.runOnUiThread()例如,您可以调用 。

于 2010-12-09T02:57:46.337 回答