how to start service from fragments

44,344

Solution 1

Replace

startService(new Intent(getActivity(),myPlayService.class));

with

getActivity().startService(new Intent(getActivity(),myPlayService.class));

Solution 2

To start service from a fragment use

Java

requireActivity().startService(new Intent(getContext(), ServiceName.class));

Kotlin

requireActivity().startService(Intent(context, ServiceName::class.java)
Share:
44,344
Swap-IOS-Android
Author by

Swap-IOS-Android

Only 3 words about me. Android, iOS, php SOreadytohelp

Updated on July 09, 2022

Comments

  • Swap-IOS-Android
    Swap-IOS-Android almost 2 years

    I want to start service from fragment from a list view item. I am trying to call service with:

    startService(new Intent(getActivity(),myPlayService.class));
    

    But it wont work at all. How do i call my service from fragments? Is there any another way to start service?

  • IgorGanapolsky
    IgorGanapolsky almost 10 years
    But it wouldn't even compile anyway if he didn't use getActivity()
  • CACuzcatlan
    CACuzcatlan over 9 years
    @IgorGanapolsky, that's what the original post was saying. They were asking how to make it compile.