Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

multithreading - Execute code on main thread in Android without access to an Activity?

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.

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

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.

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?

Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...