android - Handler如何影响onReceiveResult(ResultReceiver)的调用方式?

标签 android handler

看,我有以下代码:

我的行动:

final Intent intent = new Intent(getApplicationContext(), MyService.class)
.putExtra(UploadService.EXTRA_RESULT_RECEIVER, new ResultReceiver(null) {
            @Override
            protected void onReceiveResult(int resultCode, Bundle resultData) {
                super.onReceiveResult(resultCode, resultData);
                String result = resultData.getString(MyService.EXTRA_RESULT_SUCCESS);
                ...
                imageView.setBackgroundDrawable(bitmap);// here my code fails
            }
        })

我的服务:

    Bundle b = new Bundle();
    b.putString(EXTRA_RESULT_SUCCESS, response.toString());
    resultReceiver.send(0, b);

我的应用程序在“imageView.setBackgroundDrawable(bitmap)”行失败,但出现以下异常:

11-13 16:25:38.986: ERROR/AndroidRuntime(3586): FATAL EXCEPTION: IntentService[MyService]
    android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.

但是当我这样定义接收器时(使用处理程序),这不会发生:

new ResultReceiver(new Handler()){.../*here goes the same code as in the first example. nothing has been changed*/}

所以。当我传递默认处理程序时它不会失败。我问为什么?在这两种方式中,我的代码都会被调用,但是当没有指定处理程序时,它会失败。 Handler有什么影响?

最佳答案

Handler 绑定(bind)到 Android 框架并确保在 Handler 的回调中运行的任何代码都在父 Activity 的主 Looper 线程上执行,这是所有 Activity 生命周期回调和 UI 调用的地方。如果你真的想了解它是如何工作的,你可以浏览 Github 上的源代码,但在 Handler 中运行代码几乎可以保证把事情放在正确的地方。

关于android - Handler如何影响onReceiveResult(ResultReceiver)的调用方式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8112319/

相关文章:

java - 如何将 "\n "替换为新行?

c# - 如何在 Windows 窗体应用程序中使用多线程来更新进度条?

ios - 如何捕获 "incoming call"而不是引导到后台?

asp.net - 何时使用 HttpHandlers 和 HttpModules?

java - 无法从java应用程序执行连续的adb命令

android - 从图库中挑选照片并在 ImageView 中显示

android - 在某些设备上使用 SENDTO 发送带附件的电子邮件不起作用

android - android中监听器和接口(interface)的区别?

java - 如何在两个for循环中分别使用postDelayed或sleep两次

android - Android项目导出时出现Proguard错误-系统找不到指定文件