在Android中的主线程上执行代码而不访问Activity? [英] Execute code on main thread in Android without access to an Activity?

查看:282
本文介绍了在Android中的主线程上执行代码而不访问Activity?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个可启动并维护后台线程的Android服务.

I have an Android service that starts and maintains a background thread.

有时,后台线程需要在主线程上进行回调.我对如何做到这一点感到困惑.

From time to time, the background thread needs to do a callback on the main thread. I'm stumped as to how to do this.

我无法调用this.runOnUiThread,因为"this"是Service的实例,不是Activity的实例,并且Service没有runOnUiThread方法.

I can't call this.runOnUiThread because "this" is an instance of Service, not Activity, and a Service doesn't have the runOnUiThread method.

我也无法创建或执行AsyncTask,因为AsyncTask的文档说构造函数和execute方法都必须从UI线程中调用.

I also can't create or execute an AsyncTask, because the documentation for AsyncTask says that both the constructor and the execute method must be invoked from the UI thread.

我是否需要维护对使用该服务的活动的引用并调用其runOnUiThread方法,或者是否有另一种方法可以在UI线程上运行某些东西?

Do I need to maintain a reference to the activity that is using the service and call its runOnUiThread method, or is there another way to run something on the UI thread?

谢谢.

推荐答案

如果我(由于某种原因或其他原因)不直接访问Activity,那么我会不时使用以下代码;

I'm using following code from time to time if I do not hold direct access to Activity (for a reason or another);

new Handler(Looper.getMainLooper()).post(mYourUiThreadRunnable);

这篇关于在Android中的主线程上执行代码而不访问Activity?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆