gpt4 book ai didi

Android startService() 需要很长时间才能返回到 UI 线程

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:51:07 25 4
gpt4 key购买 nike

第一次启动时,我的用例(大致)如下:

  1. activity 启动一个服务
  2. 服务获取数据并将其保存在数据库中
  3. 服务通知有 Intent 的 Activity
  4. 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);
}
}

最佳答案

来自指南主题Services :

Caution: A services runs in the same process as the application in which it is declared and in the main thread of that application, by default. So, if your service performs intensive or blocking operations while the user interacts with an activity from the same application, the service will slow down activity performance. To avoid impacting application performance, you should start a new thread inside the service.

这不会因为您从 AsyncTask 调用 startService 而改变。

关于Android startService() 需要很长时间才能返回到 UI 线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8404193/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com