【问题标题】:ProgressDialog freezes when trying to run a service with an asynctask尝试使用异步任务运行服务时,ProgressDialog 冻结
【发布时间】:2010-11-15 13:50:21
【问题描述】:

我的异步任务中有这段代码:

@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(),它就可以正常工作。

谁能告诉我为什么会这样以及如何解决这个问题?

谢谢

【问题讨论】:

    标签: android service android-asynctask


    【解决方案1】:

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

    【讨论】:

    • 您能否详细说明为什么不应该从 AsyncTask 启动服务?有兴趣了解原因。
    【解决方案2】:

    如果你在哪里使用SystemClock.sleep()?你的意思是不是创建服务?好吧,首先在 UI 线程上创建服务和任何其他活动。所以在 asynctask 中启动你的服务什么都不做。

    【讨论】:

    • 是的,而不是创建服务。创建服务会冻结 UI,但 sleep() 不会。那我该怎么做呢?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-11
    • 2022-06-21
    • 2016-05-23
    • 1970-01-01
    • 1970-01-01
    • 2020-05-10
    相关资源
    最近更新 更多