英文:
android: why do we need Runnables in JobIntentService?
问题
以下是翻译好的部分:
我正在使用JobIntentService
进行开发,而文档中有这个示例:
@Override
protected void onHandleWork(Intent intent) {
...
toast("执行中");
...
}
@Override
public void onDestroy() {
super.onDestroy();
toast("所有工作完成");
}
final Handler mHandler = new Handler();
// 用于显示消息的辅助方法
void toast(final CharSequence text) {
mHandler.post(new Runnable() {
@Override public void run() {
Toast.makeText(JsInvokerJobService.this, text, Toast.LENGTH_SHORT).show();
}
});
}
作为一个对Android新手,我不明白为什么他们在onHandleWork
和onDestroy
方法中没有直接使用Toast.makeText
,而是将其包装在一个Runnable
中。关于Runnable
的文档并没有提供太多帮助。这是特定于JobIntentService
还是其他情况也适用?在onHandleWork
方法中应该放入什么内容,什么内容应该放到Runnable
中去?
英文:
I am playing with JobIntentService
, and the docs have this example:
@Override
protected void onHandleWork(Intent intent) {
...
toast("Executing");
...
}
@Override
public void onDestroy() {
super.onDestroy();
toast("All work complete");
}
final Handler mHandler = new Handler();
// Helper for showing tests
void toast(final CharSequence text) {
mHandler.post(new Runnable() {
@Override public void run() {
Toast.makeText(JsInvokerJobService.this, text, Toast.LENGTH_SHORT).show();
}
});
}
I am new to Android, and I don't understand why they wrap Toast.makeText
in a Runnable
and don't use it directly in the onHandleWork
and onDestroy
methods. The docs for Runnable don't really help. Is this specific to JobIntentService
or not? What stuff should go into the onHandleWork
method and what should be offloaded to a Runnable
?
答案1
得分: 0
我对Android还不熟悉,不明白为什么他们要将 Toast.makeText
包装在一个 Runnable
中。
这是因为 JobIntentService
在后台线程上运行,而Toast不能从后台线程中显示出来。这个处理程序会将您的可运行代码发布到UI线程的运行循环队列中,然后在UI线程上执行它。
英文:
> I am new to Android, and I don't understand why they wrap
> Toast.makeText in a Runnable
It is because JobIntentService
runs on Background thread and the Toast can't be shown from it. The handler will post in the runloop queue of the ui thread your runnable and it will get executed on it
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论