看,我有以下代码:
我的行动:
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
}
})
Run Code Online (Sandbox Code Playgroud)
为MyService:
Bundle b = new Bundle();
b.putString(EXTRA_RESULT_SUCCESS, response.toString());
resultReceiver.send(0, b);
Run Code Online (Sandbox Code Playgroud)
我的应用程序在"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.
Run Code Online (Sandbox Code Playgroud)
但是当我像这样定义接收器(带处理程序)时,这不会发生:
new ResultReceiver(new Handler()){.../*here goes the same code as in the first example. nothing has been changed*/}
Run Code Online (Sandbox Code Playgroud)
所以.当我传递默认处理程序时它不会失败.我问为什么?在这两种方式中都调用了我的代码,但是当没有Handler指定它时它会失败.Handler有什么影响?
Handler绑定到Android框架并确保在Handler的回调中运行的任何代码都在父Activity的主Looper线程上执行,该线程是进行所有Activity生命周期回调和UI调用的地方.如果你真的想了解它是如何工作的,你可以浏览Github上的源代码,但是在Handler中运行代码几乎可以保证把东西放在正确的位置.
| 归档时间: |
|
| 查看次数: |
3157 次 |
| 最近记录: |