2012-11-21 40 views

回答

3

IntentService s已经是后台进程;没有必要从那里启动一个AsyncTask。 另外,从任何地方开始AsyncTask是'安全'的;它是帮助你多线程的辅助类。如果您在活动中使用它,请确保您不要在您的AsyncTask的doInBackground()-method中操纵View

如果你需要生成你的IntentService内多个线程,只需使用:

新的Thread(Runnable的R)。开始();

看到How to run a Runnable thread in Android?

一个例子,如果你需要调用某种回调,使用Handler。有关示例,请参阅http://www.vogella.com/articles/AndroidPerformance/article.html#handler

+4

开始一个'AsyncTask'从任何地方都不安全:http://stackoverflow.com/questions/4187960/asynctask-and-looper-prepare-error - 它只打算从主线程启动,可能工作如果你在'onHandleIntent'里面启动它,因为它有一个Looper – zapl

+1

如果我在onHandleIntent()里面不使用asyncTask?它里面的代码仍然会在后台运行? – Rookie

+1

@zapl,感谢您的评论。 Raghav:只需调用你想要调用的方法;因为IntentService在不同的线程中运行,所以您的UI不会冻结。如果出于任何原因想要在IntentService中产生多个线程,只需使用新线程(Runnable r).start();看例子在http://stackoverflow.com/questions/1921514/how-to-run-a-runnable-thread-in-android – Reinier

0

AsyncTask类用于提供一种机制来实现多线程,因此您的事件线程不会被绞死,但是在您使用服务时,您不应该使用服务中的AsyncTask,而是您可以使用线程,如果某些长时间运行的任务要执行,则在Service中。

0

如果您确实需要在IntentService中使用AsyncTask,则可以在AsyncTask中创建一个方法,该方法调用de doInBackGround和onPostExecute。事情是这样的:

void executeFlowOnBackground(Params params) { 
    onPostExecute(doInBackground(params)); 
} 

在我来说,我这样做是因为所有App请求中通过扩展的AsyncTask类制成,并且由于执行的是难度重构代码。

+0

我纠正了错字。请确保不要在下次发生这样的错字... –