2013-12-21 48 views
0

我已经下载和解析与Jsoup网页,显示在列表中的内容。这个过程需要一段时间,所以我实现Callable接口做任务在另一个线程,并得到结果返回。 问题是,过程中需要阻塞UI。可赎回阻塞UI

public class GetListaNotizie implements Callable<ArrayList<Notizia>> { 

static ArrayList<Notizia> getNotizieBySezione() { 
    [...] Long process 
    return notizie; 
} 

@Override 
public ArrayList<Notizia> call() throws Exception { 
    return getNotizieBySezione(); 
} 
} 

然后:

final ExecutorService service; 
final Future<ArrayList<Notizia>> task; 
service = Executors.newFixedThreadPool(1); 
task = service.submit(new GetListaNotizie()); 
try { 
    ArrayList<Notizia> notizie = task.get(); 
    lvListaNotizie.setAdapter(new RiempiLista(activity, notizie)); 
} catch (InterruptedException e) { 
    e.printStackTrace(); 
} catch (ExecutionException e) { 
    e.printStackTrace(); 
} 

我缺少什么?

+0

'task.get()'调用被阻塞。无论如何,你不需要使用执行者和期货来重新发明轮子。 Android已经有一个['AsyncTask'](http://developer.android.com/reference/android/os/AsyncTask.html)类,它正是为这些类型的任务而准备的。 –

回答

1

因为......你提交Callable到池中,然后明确阻塞线程等待它完成。

ArrayList<Notizia> notizie = task.get(); 

我错过了您的问与答 Android的标签。你正在重新发明车轮。 Android为这个用例提供了AsyncTask。看到它是如何工作的例子Processes and Threads下的AsyncTask例子。

原来的答复如下


你需要你的Callable更新/它结束时通知UI。一个可能的办法是传递给你提你的Callable列表的引用。

编辑从添加注释:

现在,您提交Callable到池中。然后你坐在那里等待它完成(阻止UI线程)。通过构造

lvListaNotizie.setAdapter(new RiempiLista(activity, notizie)); 

通行证lvListaNotizieGetListaNotizie和有这种情况发生在call()末代替列表返回到Future的:那你做到这一点。我不知道lvListaNotizie是什么;如果它不是线程安全的,你会想同步它。

+0

我不确定我明白你的意思。你能写一个例子吗? –