2010-11-15 47 views
1

我有我的AsyncTask这里面代码:ProgressDialog试图用的AsyncTask运行服务时冻结

@Override 
protected void onPreExecute() { 
    waitDialog = new ProgressDialog(context);   
    waitDialog.setTitle(R.string.wait_title);   
    waitDialog.setMessage(context.getString(R.string.wait_body)); 
    waitDialog.setIndeterminate(true); 
    waitDialog.show(); 
} 

@Override 
protected Boolean doInBackground(Void... unused) { 
    Intent serviceIntent = new Intent(context, PublisherService.class); 
    saveSettings(false); 
    startService(serviceIntent); 
    return serviceIsRunning(); 
} 

对话节目,但同时我的服务正在启动(这需要几秒钟)的progressdialog被冻结。如果我在我的doInBackground()调用中使用简单的SystemClock.sleep(),它可以正常工作。

有人可以告诉我为什么会发生这种情况,以及如何解决这个问题?

谢谢

回答

1

您不应该从线程或asynctasks启动任何服务。服务可以启动自己的线程并执行所有工作。或者可以绑定到onPreExecute()中的服务并从doInBackground中调用它的方法。阅读本地服务http://developer.android.com/reference/android/app/Service.html

+0

你能否详细说明为什么不应该从AsyncTask启动服务?有兴趣了解为什么。 – Spinner 2012-08-17 13:13:02

0

如果您使用SystemClock.sleep()在哪里?你的意思是代替创建一项服务?那么首先在UI线程上创建所有服务和其他任何活动。所以在asynctask中开始你的服务什么都不做。

+0

是的,而不是创建一个服务。创建服务会冻结UI,但sleep()不会。我应该怎么做呢? – 2010-11-16 15:38:38