我从MainActivity
和Fragment
开始提供后台服务。
它会创建重复的线程吗?那么它将运行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));
它会创建重复的线程吗?那么它将运行2个服务吗?
不会只启动一项服务,只会运行一项服务
将只有一个服务正在运行。 。
它会创建重复的线程吗?那么它将运行2个服务吗?
每次调用startService()都有两种可能性。
每个Service
只存在一个实例。如果您的服务已经运行,那么如果您尝试重新启动,将会调用onStartCommand(Intent, int, int)
。
警告:服务在其托管进程的主线程中运行;除非另行指定,否则服务不会创建自己的线程,也不会在单独的进程中运行。
所以默认情况下Service
使用主线程和IntentService使用后台线程。如果你想做一些长时间运行的任务,那么使用IntentService
或在Service
中创建一个后台线程。
有关更多信息,请查看this