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

标签 android android-asynctask ui-thread

我是 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/

相关文章:

android - 如何从 Genymotion android 模拟器访问 localhost?

android - 如何仅在最短延迟后显示 ProgressBar?

android - 没有网络连接时应用崩溃

winforms - 在不存在控制对象的情况下在 UI 线程上运行代码

android - 为什么Android服务需要在UI线程上运行?

使用 AsyncTask 和 UI 更新解决方案的 Android 单元测试

android - 为什么我不允许在这种情况下使用 setOnClickListener?

android - onDestroy 被调用

android - 第二次点击/单击标记不会调用 OnMarkerClickListener

java - Android - 从其他 Activity 中的 AsyncTask 调用时,ListFragment 中的上下文不起作用