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

Does start of a Service from MainActivity and fragment duplication threads?

我从 MainActivityFragment 开始后台服务。

它会创建重复线程吗?所以这将是 2 个服务 运行?

MainActivity

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));

Will it create duplicate threads? So It will be 2 services running?

NO 只会启动一项服务,而且只会启动一项服务 运行

只有一项服务 运行. .

Will it create duplicate threads? So It will be 2 services running?

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

  1. 如果服务之前没有启动,那么它将按照其生命周期启动。 onCreate -> onStartCamm​​and 等等。

  2. 如果服务之前已启动,则只有 onStartCamm​​and() 会以您传递给它的所需意图被调用。

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

来自Android Official site

Caution: A service runs in the main thread of its hosting process; the service does not create its own thread and does not run in a separate process unless you specify otherwise.

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

更多检查this