看,我有以下代码:
我的行动:
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/