从MainActivity和片段复制线程启动服务?

问题描述 投票:0回答:3

我从MainActivityFragment开始提供后台服务。

它会创建重复的线程吗?那么它将运行2个服务吗?

主要信息

protected void onCreate(Bundle savedInstanceState) {
  //...
  context.startService(new Intent(context,gps_service.class));
//...

分段

public class FragmentThree extends Fragment {

//... Click method of the button calls
getActivity().startService(new Intent(getActivity(),gps_service.class));
java android multithreading android-fragments android-service
3个回答
2
投票

它会创建重复的线程吗?那么它将运行2个服务吗?

不会只启动一项服务,只会运行一项服务


2
投票

将只有一个服务正在运行。 。

它会创建重复的线程吗?那么它将运行2个服务吗?

每次调用startService()都有两种可能性。

  1. 如果以前未启动Service,则它将按其生命周期启动。 onCreate - > onStartCamm​​and等。
  2. 如果先前已启动Service,那么只有onStartCamm​​and()将被调用您传递给它的所需intent。

1
投票

每个Service只存在一个实例。如果您的服务已经运行,那么如果您尝试重新启动,将会调用onStartCommand(Intent, int, int)

来自Android Official site

警告:服务在其托管进程的主线程中运行;除非另行指定,否则服务不会创建自己的线程,也不会在单独的进程中运行。

所以默认情况下Service使用主线程和IntentService使用后台线程。如果你想做一些长时间运行的任务,那么使用IntentService或在Service中创建一个后台线程。

有关更多信息,请查看this

© www.soinside.com 2019 - 2024. All rights reserved.