gpt4 book ai didi

android - 如何在 Android UI 线程异步中执行一些代码?

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

我是 Android 开发新手。多年来,我一直致力于 Swing 和 SWT。 Swing 和 SWT 都有在 UI 线程同步和异步中执行代码的策略。典型的用法是在一个线程中做一些耗时的工作,然后在 UI 线程中异步显示结果。

所以我的问题是,Android 中是否有类似的策略?这是我的代码。参数runnable是一些耗时的代码。此方法将在执行期间显示一个等待对话框,然后在完成后 EXPECT 显示一个 Toast。但是 Toast 需要在 UI 线程中显示。那么该怎么做呢?

    public static void showWaitingDialog(final Activity parent, final Runnable runnable, String msg) {

if (StringUtils.isEmpty(msg)) {
msg = "processing...";
}

final ProgressDialog waitingDialog = ProgressDialog.show(parent, "Please Wait...", msg, true);

// execute in a new thread instead of UI thread
ThreadPoolUtil.execute(new Runnable() {

public void run() {
try {
// some time-consume operation
runnable.run();
} catch (Exception e) {
e.printStackTrace();
} finally {
waitingDialog.dismiss();
}
// TODO: How to display a Toast message here? execute some code in UI Thread.

}

});

}

还有关于Android UI系统的一些话吗?比如它是线程安全的,线程如何协同工作等等。非常感谢!

最佳答案

有几种方法可以做到这一点,

  • 异步任务 -

AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers. Example for using AsyncTask

  • 服务 -

A Service is an application component representing either an application's desire to perform a longer-running operation while not interacting with the user or to supply functionality for other applications to use. Example for Using Service.

  • Intent 服务 -

IntentService is a base class for Services that handle asynchronous requests (expressed as Intents) on demand. Clients send requests through startService(Intent) calls; the service is started as needed, handles each Intent in turn using a worker thread, and stops itself when it runs out of work. Example for using IntentService.

关于android - 如何在 Android UI 线程异步中执行一些代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9173299/

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