【发布时间】:2012-01-14 07:23:12
【问题描述】:
我的用例在第一次启动时(大致)如下:
- activity 启动服务
- 服务获取数据并将其保存在数据库中
- 服务根据意图通知活动
- 活动显示数据
现在我想在服务繁忙时显示进度条。问题是:
startService(new Intent(getApplicationContext(), UpdateDataService.class));
需要很长时间才能“返回”到 UI 线程。它似乎是一个同步函数(或not?)。如果服务类为空,则几乎立即处理 startService 命令。似乎 UI 线程等待 Serice 处理其工作,这根本没有意义。我试图开始(尽管看起来很愚蠢)以异步任务启动服务,同时在我的 UI 线程中显示进度条。很奇怪,这有时会起作用。有时我只是在我的服务工作时得到一个白屏,然后是一个毫秒的进度条,然后是我的 UI。
现在我的问题是:如何在不阻塞 UI 的情况下启动服务?
public class MyClass extends TabActivity {
private ProgressDialog pd;
@Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Intent intent = null;
//building some tabs here, setting some text views....
// starting service if does not exist yet
boolean serviceRunning = false;
final ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
for (final RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if ("aegir.mobile.UpdateDataService".equals(service.service.getClassName())) {
serviceRunning = true;
Log.i(MY_APP_TAG, "Service found.");
}
}
if (!serviceRunning) {
pd = ProgressDialog.show(this, "Loading...", "Setting up data.", true, false);
new StartServiceAsync().execute("");
}
}
private final Handler handler = new Handler() {
@Override
public void handleMessage(final Message msg) {
pd.dismiss();
}
};
public class StartServiceAsync extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(final String... params) {
// starting service
startService(new Intent(getApplicationContext(), UpdateDataService.class));
return null;
}
@Override
protected void onPostExecute(final String result) {
handler.sendEmptyMessage(0);
super.onPostExecute(result);
}
}
【问题讨论】:
标签: android service time synchronized