从 activity 开始在新线程中启动服务是件好事吗

Is it a good thing to starting service in new thread from activity

new Thread(new Runnable(){
            @Override
            public void run () {
                Intent firstServiceIntent=new Intent(getApplicationContext(),MyService.class);
            }
        }).start();

我必须在服务中执行后台位置更新。我在服务中使用了 LocationListner,它经常调用 onLocationChanged(),这会阻塞我的 UI 线程。如果我在 onLocationChanged() 中使用创建线程,则每次调用此方法时都会产生一个新线程。所以,我正在考虑在新线程中创建整个服务,而不是在 onLocationChanged() 中创建线程。这是一个好的解决方案还是最好的方法?感谢任何帮助。

服务运行在其托管进程的主线程中;该服务不会创建自己的线程,也不会 运行 在单独的进程中,除非您另有说明。

但是,从不同的线程启动服务看起来很难看。您可以在服务中创建一个新线程。

如果您正在使用 android 的 IntentService 组件,它将自动处理您在 onHandleIntent(...) 中的后台处理,您可以尝试...

  class YourService extends IntentService

IntentService

否则如果你使用 Service 就像

  class YourService extends Service

您可以在 onCreate()

中使用您的 自定义线程

其他

该服务将 运行 在 MainThread

Service

如果您希望您的服务在后台线程上 运行,那么您有两个选择:

  1. 使用 IntentService,Android OS 在后台线程上自动 运行。您在 IntentService 中所做的一切都将在后台线程中 运行 进行。你不需要做任何线程。

  2. 使用标准 Android Service 并在要执行工作的服务中实例化 new Thread()。默认情况下,标准 Android Service 在主线程上是 运行,因此它会阻塞您的 UI。这就是为什么你必须自己处理线程。

更多信息在这里: Android Services