本文介绍了如果它在android的同一线程中运行,为什么要使用Service的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在通过Android Developer网站中的绑定服务.我以为我对服务足够了解,但是我发现了另一种通过使用 类,尤其适用于本地服务.在那里,我感到困惑.也许我把这个概念弄错了.

I was going through Bound Service in Android Developer website. I thought I understood the service enough but I just found another way of connecting service through Using a Messenger class especially for local service. There I got confused. Maybe I got the concept wrong.

这是我对Android Service 的理解.您在以下时间创建服务

Here is my understanding of Android Service. You create a service when

  1. 您想在后台中进行单独的工作.
  2. 您要使其成为一个单独的过程.
  3. 您想使它在独立于启动它的组件的生命周期中运行.
  1. You want to do separate jobs in the background.
  2. You want to make it a separate process.
  3. You want to make it run in a lifecycle that's independent of the component that started it.

混淆是列表中的第一项,即背景的定义.后台不是线程还是进程?我从没想过它可以在主线程上运行.

Confusion is the first item in the list, the definition of the background. Isn't the background a thread or process? I never thought that it can run on the main thread.

这是有关开发页面中的服务警告.

Here is the caution of service in the dev pages about.

问题

  1. 如果服务功能仍将在主线程上运行,为什么选择使用服务?
  2. 即使耗时的工作在主线程中完成,我们是否也仅需编写服务来阻止ANR?假定该服务仅适用于我的应用程序.
  3. 是否有实际案例或理由将服务作为私有使用并在同一线程中运行?

推荐答案

应用程序主线程并不总是UI线程.例如,当Activity停止时,将调用onStop(),因此UI线程将从该Activity移走,并移至相同或不同应用程序中的另一个Activity.但是,这并不意味着该应用程序不再处于活动状态,它可以继续在后台运行,直到被操作系统或用户关闭.那么谁让它在后台运行呢?它是主线程,而不是UI线程.

Application main thread is not always the UI thread. For example, when Activity is stopped, the onStop() is invoked, hence the UI thread is taken away from that Activity and moved to another Activity within the same or a different application. However it doesn't mean the application is no longer active, it can continue working in the background until it is closed either by OS or by user. Then who keeps it running in the background? It is the main thread and not the UI thread.

什么是服务

与活动组件不同,服务没有任何图形 接口.广播接收器也用于接收广播 消息(广播,多播,单播)并执行简短任务 而服务本应像流媒体一样进行冗长的处理 音乐,网络事务,文件I/O,与数据库交互等. 由活动之类的应用程序组件启动服务时 它在后台运行,即使用户切换也可以继续运行 转移到另一个应用程序或启动组件本身已被破坏

Unlike Activity components, Services do not have any graphical interfaces. Also Broadcast Receivers are for receiving broadcast messages (broadcast, multicast, unicast) and perform short tasks whereas Services are meant to do lengthy processing like streaming music, network transactions, file I/O, interact with databases, etc. When a Service is started by an application component like an Activity it runs in the background and keeps running even if the user switches to another application or the starting component is itself destroyed

为什么要使用服务

如果您不想自己管理线程,请使用IntentService.否则,请使用AsyncTasks.

Use IntentService if you don't want to fiddle with managing threads on your own. Otherwise, use AsyncTasks.

请阅读这篇出色的文章,以详细了解,并且阅读此答案.

Please read this excellent article to understand more in detail and also read this answer.

这篇关于如果它在android的同一线程中运行,为什么要使用Service的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 20:48