主题和事件 - 最好的方法是什么?
我有一个读取通话记录的课程。这可能会持续几分钟。所以如果我不想阻塞 gui 线程,我必须使用一个线程。
在 C# 中,我启动一个线程,当数据准备好时用一个事件通知 gui 线程,并在事件中将数据提供给 gui。
但是安卓应该怎么做呢?到目前为止我读到的内容告诉我,在 android 中使用 AsyncTask 是最好的。我以这种方式使用它(伪代码):
class MyClass{
private myClassVariable;
private coid startTask(){
GetDataTask data = new GetDataTask();
data.execute(varibale);
}
private void displayData{
doAnythingUsefullHere;
}
class GetDataTask extends AsyncTask<variables>{
protected variable doInBackground(variable){
return = CallLog.getData();
}
protected void onPostExecute(variable){
myclassVariable = variable;
displayData;
}
}
}
到目前为止工作正常,但我无法以这种方式取消线程。我可以取消任务,但我必须在调用日志类的数据收集循环中检查是否调用了 onCancelled,但此函数仅在类 GetDataTask 中已知,而不在 CallLog 中已知。
有没有办法使用 AsyncTask 并使“外部”类可取消?或者我是否切换到线程和事件?在这种情况下最好的方法是什么?
I have a class which reads the calllog. This could last some minutes. So I have to use a thread if I don't want to block the gui thread.
In C# I start a thread, notify the gui thread with a event when the data is ready and give the data to the gui within the event.
But how should I do it with android? What I read so far told me that's the best to use AsyncTask with android. I use it in this way (Pseudo code):
class MyClass{
private myClassVariable;
private coid startTask(){
GetDataTask data = new GetDataTask();
data.execute(varibale);
}
private void displayData{
doAnythingUsefullHere;
}
class GetDataTask extends AsyncTask<variables>{
protected variable doInBackground(variable){
return = CallLog.getData();
}
protected void onPostExecute(variable){
myclassVariable = variable;
displayData;
}
}
}
Works fine so far, but I can't cancel the thread in this way. I could cancel the task, but I have to check within the data collect loop of the calllog class if the onCancelled is called but this function is only known in the class GetDataTask and not in CallLog.
Is there a way to use AsyncTask and make "outside" classes cancelable? Or have I switch to Threads and events? What's the best way in this situation?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这可能是您正在寻找的:取消正在执行的 AsyncTask 的理想方法?
Could this be what you are looking for: Ideal way to cancel an executing AsyncTask ?