android: 为什么在JobIntentService中需要使用Runnables呢?

huangapple go评论75阅读模式
英文:

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新手,我不明白为什么他们在onHandleWorkonDestroy方法中没有直接使用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

huangapple
  • 本文由 发表于 2020年9月2日 00:18:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/63691598.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定